27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6. Exit and Exit Status<br />

...there are dark corners in the Bourne shell, and<br />

people use all of them.<br />

Chet Ramey<br />

The exit command may be used to terminate a script, just as in a C program. It can also return a value, which<br />

is available to the script's parent process.<br />

Every command returns an exit status (sometimes referred to as a return status ). A successful command<br />

returns a 0, while an unsuccessful one returns a non−zero value that usually may be interpreted as an error<br />

code. Well−behaved UNIX commands, programs, and utilities return a 0 exit code upon successful<br />

completion, though there are some exceptions.<br />

Likewise, functions within a script and the script itself return an exit status. The last command executed in the<br />

function or script determines the exit status. Within a script, an exit nnn command may be used to deliver<br />

an nnn exit status to the shell (nnn must be a decimal number in the 0 − 255 range).<br />

When a script ends with an exit that has no parameter, the exit status of the script is the exit status of the<br />

last command executed in the script (not counting the exit).<br />

$? reads the exit status of the last command executed. After a function returns, $? gives the exit status of the<br />

last command executed in the function. This is Bash's way of giving functions a "return value". After a script<br />

terminates, a $? from the command line gives the exit status of the script, that is, the last command executed<br />

in the script, which is, by convention, 0 on success or an integer in the range 1 − 255 on error.<br />

Example 6−1. exit / exit status<br />

#!/bin/bash<br />

echo hello<br />

echo $?<br />

lskdf<br />

echo $?<br />

# Exit status 0 returned because command executed successfully.<br />

# Unrecognized command.<br />

# Non−zero exit status returned because command failed to execute.<br />

echo<br />

exit 113<br />

# Will return 113 to shell.<br />

# To verify this, type "echo $?" after script terminates.<br />

# By convention, an 'exit 0' indicates success,<br />

#+ while a non−zero exit value means an error or anomalous condition.<br />

$? is especially useful for testing the result of a command in a script (see Example 12−27 and Example<br />

12−13).<br />

The !, the logical "not" qualifier, reverses the outcome of a test or command, and this affects its exit<br />

status.<br />

Example 6−2. Negating a condition using !<br />

Chapter 6. Exit and Exit Status 38

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!