Reputation: 35
if [ $? -ne 0 ]; then echo "error"; else echo "success"; fi
succeeds, and
if [ ! -f index.html ]; then echo "error"; else echo "success"; fi
succeeds, but for some reason
if [ ! -f index.html ] || [ $? -ne 0 ]; then echo "error"; else echo "success"; fi
fails.
In my case "index.html" exists and $? = 0
Upvotes: 1
Views: 155
Reputation: 113984
if [ ! -f index.html ] || [ $? -ne 0 ]
The value of $?
there reflects the exit code of [ ! -f index.html ]
. Since index.html
exists, that statement results in a nonzero exit code.
Try instead:
if [ $? -ne 0 ] || [ ! -f index.html ] ; then echo "error"; else echo "success"; fi
Because [ $? -ne 0 ]
is executed first, the value of $?
will reflect the exit code of whatever the prior command was and not the result of [ ! -f index.html ]
.
Another possibility is to put both tests into a single conditional expression:
if [ ! -f index.html -o $? -ne 0 ]; then echo "error"; else echo "success"; fi
Because there is a now a single test expression, bash evaluates $?
before the ! -f index.html
test is run. Consequently, $?
will be the exit code of whatever the prior command was.
Upvotes: 3
Reputation: 2063
Every command you execute changes $?
. It is best to store this immediately in a new variable and then check it at your leisure.
Upvotes: 0
Reputation: 51693
Try this instead:
if [[ ! -f index.html || $? -ne 0 ]]; then echo "error"; else echo "success"; fi
Upvotes: 0