Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does if [[ $? -ne 0 ]]; mean in .ksh

Tags:

linux

bash

unix

ksh

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

like image 488
Rahul sawant Avatar asked Nov 22 '13 15:11

Rahul sawant


People also ask

What is if $? 0 in shell script?

$? 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.

What is $? $# $*?

$# 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 ...).

What is the meaning of $? In shell script?

$? - 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.

What is role of $0 $? And $# in shell scripting?

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.


Video Answer


2 Answers

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.

like image 192
bishop Avatar answered Oct 21 '22 15:10

bishop


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 success
like image 6
anubhava Avatar answered Oct 21 '22 14:10

anubhava