This question is a follow-up to Bash conditional based on exit code of command .
I understand, and have made use of the accepted answer to that question:
$ cat ./txt
foo
bar
baz
$ if ! grep -Fx bax txt &>/dev/null; then echo "not found"; fi
not found
$
But I can't figure out the syntax to pull off a seemingly simple twist to the premise: how can I write a conditional for a specific exit code of a command?
This post pointed out that grep
might fail with error code > 1; so I wanted to write the above conditional to print "not found" specifically if grep
returned error code 1. How can I write such a statement? The following don't seem to work (I'm obviously flailing):
$ # Sanity-check that grep really fails with error code 1:
$ grep -Fx bax txt &>/dev/null
$ echo $?
1
$
$
$ if grep -Fx bax txt &>/dev/null -eq 1; then echo "not found"; fi
$ if grep -Fx bax txt &>/dev/null == 1; then echo "not found"; fi
$ if grep -Fx bax txt &>/dev/null = 1; then echo "not found"; fi
$ if [ grep -Fx bax txt &>/dev/null -eq 1 ]; then echo "not found"; fi
$ if [ grep -Fx bax txt &>/dev/null == 1 ]; then echo "not found"; fi
$ if [ grep -Fx bax txt &>/dev/null = 1 ]; then echo "not found"; fi
$
Note: I'm specifically trying to avoid running the command first, then using $?
in the conditional, for the reasons pointed out by the accepted answer to the first noted post.