0



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.

3
  • 1
    You are using the exit status in exactly the way it is intended to be used. Commented Nov 18, 2016 at 3:15
  • @chepner, well -- ideally, one should be directly evaluating it in a conditional rather than referring to $?. Commented Nov 18, 2016 at 3:38
  • With respect to grepping ps, by the way, see also ProcessManagement, particularly section 3.2 if you're writing software responsible for making sure a service is running -- there are tools specifically built for the purpose built into almost all operating systems. Commented Nov 18, 2016 at 15:28

1 Answer 1

3

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

This still has the same effect -- if COMMAND; then ... checks the exit status of COMMAND -- but without an extra layer of indirection.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank, that is kind of answer I was expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.