When I automate actions using Bash, I often use the return value of an Unix command to test things like : If a string is present in a file (grep) or if a process is running (ps aux + grep).
Here is an exemple, grep will return 1 if nothing matches and 0 if there is at least one result.
$ ps aux | grep process_that_doesntexist | grep -v grep
$ echo $?
$ ps aux | grep init | grep -v grep
root 1 0.0 0.1 135188 6660 ? Ss 01:43 0:00
$ echo $?
ps is not a good practice. Use
pgrep instead, if your operating system provides it.
However, in general, yes, using exit status to determine whether
grep has succeeded in matching content is entirely appropriate. That said, instead of referring to
$?, instead evaluate directly in your conditionals:
# When possible, do this: if grep -q -e value <input; then echo "found value" >&2 else echo "did not find value" >&2 fi
# ...not this: grep -q -e value <input if [ "$?" -eq 0 ]; then echo "found value" >&2 else echo "did not find value" >&2 fi