Risposte:
Qualsiasi versione conforme a POSIX digrep ha l'interruttore -qper quiet:
-q
Quiet. Nothing shall be written to the standard output, regardless
of matching lines. Exit with zero status if an input line is selected.
In GNU grep (e possibilmente in altri) puoi usare anche sinonimi a opzione lunga:
-q, --quiet, --silent suppress all normal output
La stringa esiste:
$ echo "here" | grep -q "here"
$ echo $?
0
La stringa non esiste:
$ echo "here" | grep -q "not here"
$ echo $?
1
Devi semplicemente combinare grep -q <pattern>con un controllo immediato del codice di uscita per l'ultimo processo a quit ( $?).
Puoi usarlo per creare un comando come questo, ad esempio:
uname -a | grep -qi 'linux' ; case "$?" in "0") echo "match" ;; "1") echo "no match" ;; *) echo "error" ;; esac
Opzionalmente puoi sopprimere l'output in questo STDERRmodo:
grep -qi 'root' /etc/shadow &> /dev/null ; case "$?" in "0") echo "match" ;; "1") echo "no match" ;; *) echo "error: $?" ;; esac
Questo stamperà error: 2dalla casedichiarazione (supponendo che non abbiamo privilegi per leggere /etc/shadowo che il file non esiste), ma il messaggio di errore da grepverrà reindirizzato a /dev/nullin modo da non mai vedere.
echo $?segreprestituisce un codice di uscita diverso da zero.