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
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
$# Stores the number of command-line arguments that were passed to the shell program. $? Stores the exit value of the last command that was executed. $0 Stores the first word of the entered command (the name of the shell program). $* Stores all the arguments that were entered on the command line ($1 $2 ...).
$? - It gives the value stored in the variable "?". Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) . Follow this answer to receive notifications.
If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh . Show activity on this post. They are called the Positional Parameters.
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.
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 successIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With