Excerpts from Simplify, Automate, Liberate! For Unix/Linux System Administrators
written by Gerald Yong
You have a script, and inside the script you call an external command. You want to know if the command has succeeded or failed, and take appropriate action. For example, you may want to know if the scp command that copies a local file to a remote destination was successful in the following example:
Obtain the exit code of the command from the shell variable $? .
If the external command returns a message upon success or failure, then you can store the output of the external command into a variable using a backtick operator.
Otherwise, you can capture the exit code of the command using the shell variable $? .
This only works if the command adopts standard behaviour of returning an exit code of 0 when the command is successful, and non-zero when there are any errors during the execution of the command.
For the above example:
It’s always a good practice to have your scripts return 1 or some non-zero value when there is an error, and 0 when the script has run successfully. That way, if this script is called from within another script, that script can also check the exit code to see if this script has executed successfully.
Note that if you run multiple commands, then $? will store the exit code of the last command run. So if you wish to check for the success or failure of each command, you will need to test $? after each command has been executed.
This method also works if you have many functions in your script. In the following example, there are 3 functions, each will return 0 if the function runs successfully, and 1 if the function has an error. The main program calls each function in turn, and checks their exit code. If any of the function fails, the program exits with an exit code of 1.
Need more information? Looking for expert advice to implement a mid-range to
enterprise level backup/storage solution in your organisation?
Click on the image below to contact us!