5.21. Termination and Exit CodesEvery Linux process terminates with an exit value. By convention, an exit value of 0 means that the process completed successfully, and a nonzero exit value indicates failure. All built-in commands return 1 if they fail. In Bash and the Korn, the special shell variable $? always contains the value of the previous command's exit code. In the C shell, the $status variable holds the exit code. In the following example, the date utility succeeded, whereas the gcc and gawk utilities failed: $ date ...date succeeds. Wed Feb 2 22:13:38 CST 2005 $ echo $? ...display its exit value. 0 ...indicates success. $ gcc prog.c ...compile a nonexistent program. gcc: prog.c: No such file or directory. gcc: no input files $ echo $? ...display its exit value. 1 ...indicates failure. $ gawk ...use gawk incorrectly. Usage: gawk [POSIX or GNU style options] -f progfile [--] file Usage: gawk [POSIX or GNU style options] [--] 'program' file ... ... $ echo $? ...display its exit value. 1 ...indicates failure. $ _ Any script that you write should always explicitly return an exit code. To terminate a script, use the built-in exit command (Figure 5-20).
If a shell doesn't include an explicit exit statement, the exit value of the last command is returned by default. The script in the following example returned an exit value of 3: $ cat script.sh ...look at the script. echo this script returns an exit code of 3 exit 3 $ ./script.sh ...execute the script. this script returns an exit code of 3 $ echo $? ...look at the exit value. 3 $ _ The next chapter contains some examples of scripts that make use of a command's exit value. |