How To Get Error Message In Shell 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 your scripts. The difference between a good program and a shell script error handling poor one is often measured in terms of the program's robustness. That is, the
Shell Script Exit Code
program's ability to handle situations in which something goes wrong. Exit status As you recall from previous lessons, every well-written program
Shell Script Exit On Error
returns an exit status when it finishes. If a program finishes successfully, the exit status will be zero. If the exit status is anything other than zero, then the program failed in some way.
Bash Catch Error
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 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 bash script exit on error 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, 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. Usi
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 bash error message variable Learn more about Stack Overflow the company Business Learn more about hiring developers bash if exit code or posting ads with us Unix & Linux Questions Tags Users Badges Unanswered Ask Question _ Unix & Linux Stack Exchange linux kernel error codes 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 http://linuxcommand.org/wss0150.php 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 http://unix.stackexchange.com/questions/97101/how-to-catch-an-error-in-a-linux-bash-script "${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 372k696751126 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 pathnames. You then commented later that you only wanted to check for directory
March 20, 2016 in Debian Linux, FreeBSD, Linux, OpenBSD, RedHat/Fedora Linux, Shell scripting, Suse Linux, Ubuntu Linux, UNIXWhile writing a shell script you may need to display an error message. For example, if you failed to http://www.cyberciti.biz/tips/shell-displaying-error-messages.html open /etc/passwd file you want to show an error message.
The old methodYou http://www.unix.com/shell-programming-and-scripting/108220-how-capture-actual-error-message-when-command-fails-execute.html can write something as follows on bash using the if statement to test a conditioncat /etc/shadow 2>/dev/null if [ $? -ne 0 ]; then echo "Failed to open file"; exit 1 ; fiThe new way: OR || control operatorHowever, you can use the control operator || (or lists). It has the form as shell script follows: command1 || command2 command2 is executed if and only if command1 returns a non-zero exit status. For example: $ cat /etc/shadow 2>/dev/null || echo "Failed to open file" This way you display an error message. Another option is to create die shell function:#!/bin/bash function die(){ echo "$1" exit 1 } # ... # ... other code cat /etc/shadow 2>/dev/null || die "Failed to open shell script exit file" # rest of my scriptAND (&&) control operatorSimilarly you can use AND (&&) control operator. It has the form/syntax: command1 && command2 The command2 is executed if, and only if, command1 returns an exit status of zero. For example: $ cat /etc/shadow 2>/dev/null && echo "I can open /etc/shadow file." You can combine both to produce useful message in a script:#!/bin/bash ... tar -zcf /dev/st0 /data2 && echo "/data2/ added to backup device" || echo "Warning: Cannot add /data2/ to backup device." .... Share this on:TwitterFacebookGoogle+Download PDF version Found an error/typo on this page?About the author: Vivek Gite is a seasoned sysadmin and a trainer for the Linux/Unix & shell scripting. Follow him on Twitter. OR read more like this:How do I find the exit status of a remote command executed via ssh?BASH Shell: How to run several commands in Sequence or all at onceHowTo: Debug a Shell Script Under Linux or UNIXBash shell script tip: Run commands from a variableTest your Samba server for configuration errorsLinux / UNIX: Find Out If a Directory Exists or NotTake action or execute a command based upon shell script nameLinux/UNIX: Find Out If File Exists With CScripting Unix shell scripting - KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and shell scripts and shell scripting languages here. Search Forums Show Threads Show Posts Tag Search Advanced Search Unanswered Threads Find All Thanked Posts Go to Page... unix and linux operating commands How to capture actual error message when a command fails to execute Shell Programming and Scripting Thread Tools Search this Thread Display Modes #1 04-26-2009 prathima Registered User Join Date: Apr 2008 Last Activity: 26 April 2009, 12:49 PM EDT Posts: 5 Thanks: 0 Thanked 0 Times in 0 Posts How to capture actual error message when a command fails to execute I want to capture actual error message in case the commands I use in my shell script fails. For eg: ls -l abc.txt 2>>errorlog.txt In this case I understand the error message is written to the errorlog.txt and I assume its bacause the return code from the command ls -l abc might return 2 if "abc" doesnt exists. My question is: How about if the command return non zero return code and is not equal to 2? I want to do something like this: ls -l abc.txt if [$? -ne 0] then echo $errorMessage >> errorlog.txt fi where I want actual error message that the command has returned to be written to errorlog.txt. Just for understanding I used $errorMessage but I assume there should be some means to capture the actual error message which can later be stored in errorMessage or written directly to errorlog.txt. Can someone please help? Remove advertisements Sponsored Links prathima View Public Profile Find all posts by prathima #2 04-26-2009 devtakh Unix Enthusiatic Join Date: Oct 2007 Last Activity: 21 August 2013, 5:20 AM EDT Location: Bangalore Posts: 738 Thanks: 0 Thanked 7 Times in 7 Posts Quote: Originally Posted by prathima I want to capture actual erro