I understand that EXIT command causes the shell or program to terminate. But what is the difference between the below:
exit 2
exit 3
exit 4
exit $?
how is exit 2 different from exit 3 and so on
I understand that EXIT command causes the shell or program to terminate. But what is the difference between the below:
exit 2
exit 3
exit 4
exit $?
how is exit 2 different from exit 3 and so on
This is only an exit code. 0 is for fine exit, otherwise it's the error code. $?
is a shell variable storing the previous exit value (so the program which ran before your one).
The exit
command takes a single value which is the value of the process (e.g. shell) return code. $?
is the return code from the last command executed by the shell.
For instance, the script which exits with a return code corresponding to the first argument:
#!/bin/sh
exit $1
Would give you:
# ./script 1
# echo $?
1
# ./script 2
# echo $?
2
Note on most UNIX systems, the return code is limited to a numeric value between 0 and 255, with 0 indicates success and 1-255 providing error information (specific to each process).
From the Advanced Bash-Scripting Guide, Chapter 6: Exit and Exit Status:
The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script's parent process.
So the exit
command lets you assign your own exit value, which you could describe in its man page, for example.
The $?
will return the exit code of the previous command. For example; You write a script that executes cat example.txt
, which results exit code 1. If you then do exit $?
, your script will exit with the same code as cat example.txt
$?
here: What is the $? variable in shell scripting?