Pierre-Luc Bertrand
Pierre-Luc Bertrand

Reputation: 740

Bash exit code of the test part should not be 0

Why is this bash script returning an exit code of 0?

$ if [ $NonExistent != "something" ]; then echo good; fi; echo $?
-bash: [: !=: unary operator expected
0

I've tried putting the script in a file and adding

set -e
set -o pipefail

but it still returns 0. Assuming I can't modify this script and can only invoke it, is there a way I could know that the script failed?

Upvotes: 1

Views: 73

Answers (1)

melpomene
melpomene

Reputation: 85767

It's returning 0 because

https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

if

[...]

The return status is the exit status of the last command executed, or zero if no condition tested true.

As for knowing that the script failed: What exactly do you mean by "failed"? It runs through successfully.

You could test whether the output starts with good if you want to know whether the condition was true or not.

Upvotes: 3

Related Questions