Issue
Consider the following bash
code:
if [ "$a" = "foo"]
then
echo "TRUE"
fi
echo $?
we get:
bash: [: missing `]'
0
So basically, the test in the if fails due to a typo (no space between "foo"
and ]
), but the exit code of the whole if
is still 0
aka. success.
This answer explains why the exit code is 0
(we get the exit code of if
which is 0
because nothing was true
).
So far so good, but this behavior is extremely dangerous as it can lead to silent errors. Is there a way to rewrite the condition, or change any bash
settings, such that typos like these trigger a non-zero exit of the script / ìf
?
Solution
Yes, there is a way to rewrite the condition: Don't use [
.
#!/bin/bash -e
if [[ "$a" = "foo"]]
then
echo "TRUE"
fi
echo "REACHED"
properly results in:
yourscript: line 1: syntax error in conditional expression
You can see this tested at https://ideone.com/ZH1Znb
Alternately, you can check the exit status:
#!/bin/bash -e
# using legacy ksh syntax because some versions of bash are picky
# about function names with POSIX-y syntax; in new bash, though,
# this also works with `[() {` as the first line.
function [ {
builtin [ "$@" || {
rc=$?
case $rc in
0|1) return $?;;
*) echo "ERROR: Bad test syntax" >&2; exit "$rc";;
esac
}
}
if [ "$a" = foo]
then
echo "TRUE"
fi
echo "REACHED"
but this is obviously a horrid abomination.
Note that while the above examples use set -e
, this feature has serious pitfalls, and I strongly advise against its use.
Answered By - Charles Duffy Answer Checked By - Dawn Plyler (WPSolving Volunteer)