Bash Shell Script Exit On Error
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring shell script halt on error developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question
Linux Shell Script Exit On Error
x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them;
Bash Shell Script Function Return Value
it only takes a minute: Sign up In a bash script, how can I exit the entire script if a certain condition occurs? up vote 234 down vote favorite 49 I'm writing a script in Bash to test some
Bash Get Exit Status
code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I'll just abort the tests. Is there a way I can do this without wrapping the entire script inside of a while loop and using breaks? Something like a dun dun dun goto? bash scripting share|improve this question asked Sep 4 '09 at 9:51 samoz 20.7k39108167 add a comment| 6 Answers 6 active oldest votes up vote 221 bash exit status variable down vote accepted Try this statement: exit 1 Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings. share|improve this answer edited Aug 7 '15 at 7:10 flying sheep 2,96722245 answered Sep 4 '09 at 9:53 Michael Foukarakis 20.5k35089 42 0 isn't good status to exit with if an error happens. –Michał Górny Sep 4 '09 at 9:59 4 You're right, edited for clarity. –Michael Foukarakis Sep 4 '09 at 10:00 @MichałGórny what would be a good status code? –CMCDragonkai May 14 '14 at 2:39 3 @CMCDragonkai, usually any non-zero code will work. If you don't need anything special, you can just use 1 consistently. If the script is meant to be run by another script, you may want to define your own set of status code with particular meaning. For example, 1 == tests failed, 2 == compilation failed. If the script is part of something else, you may need to adjust the codes to match the practices used there. For example, when part of test suite run by automake, the code 77 is used to mark a test skipped. –Michał Górny May 14 '14 at 8:00 add a comment| up vote 396 down vote Use set -e #!/bin/bash set -e /bin/command-that-fails /bin/command-that-fails2 The script will terminate after the first line that fails (returns nonzero exit code). In this case, command-that-fails2 will not run. If you were
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 your scripts. The difference between a good program and a poor one is often measured in terms of the program's shell script error handling robustness. That is, the program's ability to handle situations in which something goes wrong. Exit status exit bash shell As you recall from previous lessons, every well-written program returns an exit status when it finishes. If a program finishes successfully, the exit bash if exit code 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 http://stackoverflow.com/questions/1378274/in-a-bash-script-how-can-i-exit-the-entire-script-if-a-certain-condition-occurs that your scripts return a meaningful exit status when they finish. I once had a Unix system administrator 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 http://linuxcommand.org/wss0150.php 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, you can examine the contents of the $? environment variable. $? will contain the exit status of the last command executed. You can see this work with the following: [me] $ true; echo $? 0 [me] $ false; echo $? 1 The true and false commands are programs that do nothing except return an exit status of zero and one, respectively. Using them, we can see how the $? environment variable contains the exit status of the previous program. So to check the exit status, we could write the script this way: # Check the exit status cd $some_directory if [ "$?" = "0" ]; then rm * else echo "Cannot change directory!" 1>&2 exit 1 fi In this version, we
Bash Prompts About Writing Robust Bash Shell Scripts Many people hack together shell scripts quickly to do simple tasks, but these soon take on a life of their own. Unfortunately shell scripts are full of subtle effects which result in scripts failing in unusual ways. It's possible to write scripts http://www.davidpashley.com/articles/writing-robust-shell-scripts/ which minimise these problems. In this article, I explain several techniques for writing robust bash http://unix.stackexchange.com/questions/97101/how-to-catch-an-error-in-a-linux-bash-script scripts. Use set -u How often have you written a script that broke because a variable wasn't set? I know I have, many times. chroot=$1 ... rm -rf $chroot/usr/share/doc If you ran the script above and accidentally forgot to give a parameter, you would have just deleted all of your system documentation rather than making a smaller chroot. So what can you do about shell script it? Fortunately bash provides you with set -u, which will exit your script if you try to use an uninitialised variable. You can also use the slightly more readable set -o nounset. david% bash /tmp/shrink-chroot.sh $chroot= david% bash -u /tmp/shrink-chroot.sh /tmp/shrink-chroot.sh: line 3: $1: unbound variable david% Use set -e Every script you write should include set -e at the top. This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is bash shell script that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit. Using -e gives you error checking for free. If you forget to check something, bash will do it or you. Unfortunately it means you can't check $? as bash will never get to the checking code if it isn't zero. There are other constructs you could use: command if [ "$?"-ne 0]; then echo "command failed"; exit 1; fi could be replaced with command || { echo "command failed"; exit 1; } or if ! command; then echo "command failed"; exit 1; fi What if you have a command that returns non-zero or you are not interested in its return value? You can use command || true, or if you have a longer section of code, you can turn off the error checking, but I recommend you use this sparingly. set +e command1 command2 set -e On a slightly related note, by default bash takes the error status of the last item in a pipeline, which may not be what you want. For example, false | true will be considered to have succeeded. If you would like this to fail, then you can use set -o pipefail to make it fail. Program defensively - expect the unexpected Your script should take into account of the unexpected, like files missing or directories not being created. There are seve
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow 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 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 # 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 369k666681119 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 add a comment| 5 Answers 5 active oldest votes up vote 4 down vote accepted Your script changes directories as it runs, which means it won't work with a series of relative pathn