Reputation: 425
I have a following piece of code that says if everything is executed mail a person if it fails mail the person with a error message.
if [[ $? -ne 0 ]]; then
mailx -s" could not PreProcess files" [email protected]
else
mailx -s" PreProcessed files" [email protected]
fi
done
I am new to linux coding I want to understand what if [[ $? -ne 0 ]];
means
Upvotes: 16
Views: 48379
Reputation: 39424
Breaking it down, simple terms:
[[ and ]]
... signifies a test is being made for truthiness.
$?
... is a variable holding the exit code of the last run command.
-ne 0
... checks that the thing on the left ($?
) is "not equal" to "zero". In UNIX, a command that exits with zero succeeded, while an exit with any other value (1, 2, 3... up to 255) is a failure.
Upvotes: 27
Reputation: 212374
Presumably, the snippet is part of code that looks something like:
for var in list of words; do
cmd $var
if [[ $? -ne 0 ]]; then
mailx -s" could not PreProcess files" [email protected]
else
mailx -s" PreProcessed files" [email protected]
fi
done
Which could (and should) be re-written more simply as:
for var in list of words; do
if ! cmd $var; then
message="could not PreProcess files"
else
message="PreProcessed files
fi
mailx -s" $message" [email protected]
done
The [[ $? -ne 0 ]]
clause is a hackish way to check the return value of cmd
, but it is almost always unnecessary to check $?
explicitly. Code is nearly always cleaner if you let the shell do the check by invoking the command in the if clause.
Upvotes: -1
Reputation: 785481
if [[ $? -ne 0 ]];
Is checking return code of immediately previous this if condition.
$?
means return code$? -ne 0
means previous command returned an error since 0 is considered successUpvotes: 8