Error Handling Script
Contents |
and Signals and Traps (Oh My!) - Part 1 by William Shotts, Jr. In this lesson, we're going to look at handling errors during the execution of
Shell Script Error Handling
your scripts. The difference between a good program and a poor shell script exit code one is often measured in terms of the program's robustness. That is, the program's ability to handle situations
Shell Script Exit On Error
in which something goes wrong. Exit status As you recall from previous lessons, every well-written program returns an exit status when it finishes. If a program finishes successfully, the try catch in shell script exit status will be zero. If the exit status is anything other than zero, then the program failed in some way. It is very important to check the exit status of programs you call in your scripts. It is also important that your scripts return a meaningful exit status when they finish. I once had a Unix system administrator bash script exit on error who wrote a script for a production system containing the following 2 lines of code: # Example of a really bad idea cd $some_directory rm * Why is this such a bad way of doing it? It's not, if nothing goes wrong. The two lines change the working directory to the name contained in $some_directory and delete the files in that directory. That's the intended behavior. But what happens if the directory named in $some_directory doesn't exist? In that case, the cd command will fail and the script executes the rm command on the current working directory. Not the intended behavior! By the way, my hapless system administrator's script suffered this very failure and it destroyed a large portion of an important production system. Don't let this happen to you! The problem with the script was that it did not check the exit status of the cd command before proceeding with the rm command. Checking the exit status There are several ways you can get and respond to the exit status of a program. First,
being able to handle errors helps to ensure that an unexpected event will not go on to wreck the system you are working on. Take the example below. Every week in our sample company (MyCompany.Com) Human Resources
Bash Script Trap
are going to upload a list telling us who should have access to the Expenses bash if exit code database. If a name isn’t in the list from HR we’re going to remove it from the group and that user will no
Linux Kernel Error Codes
longer be able to log expense claims: $AuthorizedUsers= Get-Content \\ FileServer\HRShare\UserList.txt $CurrentUsers=Get-ADGroupMember "Expenses Claimants" Foreach($User in $CurrentUsers) { If($AuthorizedUsers -notcontains $User) { Remove-ADGroupMember -Identity "Expenses Claimants" -User $User } } Now, you can see where this is http://linuxcommand.org/wss0150.php going to go wrong. One week HR doesn’t get around to uploading the list or, just as we are about to access the list, the file server dies. Suddenly PowerShell throws an error on the Get-Content cmdlet and the $AuthorizedUser variable remains empty. Because our script doesn’t handle errors, it continues to run and, in a very short space of time, it has removed every user from our expenses group. Pretty soon the irate phone http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell calls start flooding in and life gets a little less happy. The way to avoid all this is to catch the errors and then handle the event that caused them (which in this case is halt the script and have a shout at someone in HR). Terminating and Non-Terminating Errors One of the key things to know when catching errors is that only certain errors can be caught by default. Errors come in two types – terminating and non-terminating. A terminating error is an error that will halt a function or operation. If you make a syntax error or run out of memory, that is a terminating error. Terminating errors can be caught and handled. Non-terminating errors allow Powershell to continue and usually come from cmdlets or other managed situations. Under normal circumstances they cannot be caught by Try-Catch-Finally. The Get-Content error in the example above is a non-terminating error. Treating Non-Terminating Errors as Terminating So how do you catch a Non-Terminating error? Basically, you tell PowerShell to treat it as terminating. To do this you use the ErrorAction parameter. Every PowerShell cmdlet supports ErrorAction. By specifying -ErrorAction Stop on the end of a cmdlet you ensure that any errors it throws are treated as terminating and can be caught. In our example above we are going to change our Get-Content line to: $Authorized
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the http://unix.stackexchange.com/questions/97101/how-to-catch-an-error-in-a-linux-bash-script workings and policies of this site About Us Learn more about Stack Overflow https://www.dssw.co.uk/blog/2012-10-08-how-to-add-error-checking-to-your-shell-scripts/ the company Business Learn more about hiring developers or posting ads with us Unix & Linux Questions Tags Users Badges Unanswered Ask Question _ Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only shell script takes a minute: Sign up Here's how it works: Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top How to catch an error in a linux bash script? up vote 5 down vote favorite 1 I made the following script: # !/bin/bash # OUTPUT-COLORING red='\e[0;31m' green='\e[0;32m' NC='\e[0m' # No Color # shell script exit FUNCTIONS # directoryExists - Does the directory exist? function directoryExists { cd $1 if [ $? = 0 ] then echo -e "${green}$1${NC}" else echo -e "${red}$1${NC}" fi } # EXE directoryExists "~/foobar" directoryExists "/www/html/drupal" The script works, but beside my echoes, there is also the output when cd $1 fails on execution. testscripts//test_labo3: line 11: cd: ~/foobar: No such file or directory Is it possible to catch this? bash shell shell-script error-handling share|improve this question edited Oct 22 '13 at 22:58 Gilles 371k686741124 asked Oct 22 '13 at 10:29 Thomas De Wilde 28114 Just an FYI, you can also do this a lot simpler; test -d /path/to/directory ( or [[ -d /path/to/directory ]] in bash ) will tell you whether a given target is a directory or not, and it will do it quietly. –Patrick Oct 22 '13 at 12:36 @Patrick, that just tests if it's a directory, not if you can cd into it. –Stéphane Chazelas Oct 22 '13 at 12:54 @StephaneChazelas yes. The function name is directoryExists. –Patrick Oct 22 '13 at 13:57
article shows how to add error checking to highlight problems you might otherwise miss. Access the shell on Mac via the Terminal.app Unlike more recently designed languages, shell script does not have an easy answer for error handling. There are no common exception handling routines or ways of wrapping up large blocks of script and asking for errors to fall through to a provided subroutine. Instead shell script asks you, the author, to check individual program exit codes and branch as needed in case of an error. In practice, this means your once short script is going to get a little longer and a little more involved. Unix Exit Status Each program you run through a shell script returns an exit status. This numeric status value tells the calling script if the program completed successfully or if an error was encountered. The exit status is not visible on the command line. This makes it difficult to tell if something went wrong just by looking at the textual output of a shell script. It is possible - even common - for scripts to print nothing and yet encounter multiple errors. Let's consider this simple script: #!/bin/sh cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/. This script does one thing; it copies a single file from one volume to another using the cp program. Thankfully the cp program is chatty and will print a message if an error is encountered. That is great for us reviewing the output visually, but for the shell running our script the error will go completely unnoticed. This is a problem if our script goes on to do more work, or if we want the script to robustly deal with errors. Let's add error checking to this simple script. #!/bin/sh cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/. if [ "$?" != "0" ]; then echo "[Error] copy failed!" 1>&2 exit 1 fi We have added an if/fi block below the cp line. The new block checks the special variable