5

could anyone tell me what the following command means? I'm reading a shell script and studying what it does. But at the end of the script, the following commands appeared. I have no idea what it means.

if [ $? -ne '0' ]; then 
  exit 1
fi 

exit 0
0

1 Answer 1

8

$? is the exit status (a string, but a representation of an integer) of the last command the shell waited for, that is, not put into the background with an & marker.

A zero exit status traditionally means "success", which is different things for different programs. cat exits with zero status under almost any circumstance, with grep exits with zero status if it finds a match.

So, whatever command your script last ran, the script checks exit status. For a status not equal to zero, the script exits with a 1 status. Otherwise it exists with a zero status.

Editorially, this piece of code isn't really necessary. The shell that runs your script would exit with the exit status of the last command it invokes. Different exit statuses sometimes mean different things, so possibly a 1 exit status is important, but usually zero for success, and non-zero for failure is mostly what's necessary, and that would come from the command that exited with $? status.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .