Bash Scripting – Exiting from Script
So far in our sample scripts, we terminated things pretty abruptly. When we were finished with our last command, we just ended the script. There’s a more elegant way of completing things available to us.
Every command that runs in the shell uses an exit status to indicate to the shell that it’s finished processing. The exit status is an integer value between 0 and 255 that’s passed by the command to the shell when the command finishes running. You can capture this value and use it in your scripts.
Linux provides the $? special variable that holds the exit status value from the last command that executed. You must view or use the $? variable immediately after the command you want to check. It changes values to the exit status of the last command executed by the shell:
$ date Sat Jan 15 10:01:30 EDT 2014 $ echo $? 0 $
$ asdfg -bash: asdfg: command not found $ echo $? 127 $
$ ./myprog.c -bash: ./myprog.c: Permission denied $ echo $? 126 $
$ date %t date: invalid date ‘%t’ $ echo $? 1 $
$ ./test6 The result is 2 $ echo $? 0 $
$ cat test13 #!/bin/bash # testing the exit status var1=10 var2=30 var3=$[$var1 + $var2] echo The answer is $var3 exit 5 $
$ chmod u+x test13 $ ./test13 The answer is 40 $ echo $? 5 $
$ cat test14 #!/bin/bash # testing the exit status var1=10 var2=30 var3=$[$var1 + $var2] exit $var3 $
$ chmod u+x test14 $ ./test14 $ echo $? 40 $
Now when you run it, you get the following:
$ ./test14b The value is 300 $ echo $? 44 $
The exit status code is reduced to fit in the 0 to 255 range. The shell does this by using modulo arithmetic. The modulo of a value is the remainder after a division. The resulting number is the remainder of the specified number divided by 256. In the case of 300 (the result value), the remainder is 44, which is what appears as the exit status code.