avenetj avenetj - 20 days ago 11
Linux Question

Is it a good way to program using bash return code?




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 $?
1
$ ps aux | grep init | grep -v grep
root 1 0.0 0.1 135188 6660 ? Ss 01:43 0:00
$ echo $?
0


Is it a bad habit/way of programming ? Should bash scripts written this way should run on production servers ?

Thanks.

Answer

Grepping through 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

...instead of:

# ...not this:
grep -q -e value <input
if [ "$?" -eq 0 ]; then
  echo "found value" >&2
else
  echo "did not find value" >&2
fi