Section 5.21. Termination and Exit Codes


[Page 196 (continued)]

5.21. Termination and Exit Codes

Every 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).

Figure 5-20. Description of the exit shell command.

Shell Command: exit number

exit terminates the shell and returns the exit value number to its parent process. If number is omitted, the exit value of the previous command is used.



[Page 197]

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.




Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net