Error Handling Linux Bash
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
Linux Script Error Handling
of your scripts. The difference between a good program and a linux kernel error handling poor one is often measured in terms of the program's robustness. That is, the program's ability to handle
Linux Shell Error Handling
situations 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 bash error code successfully, the 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 bash if exit code 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 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
this page Detailed Error Handling In Bash Summary The database The mechanism Caveat Invoking the error handler The full script Usage example References
Shell Script Exit On Error
Detailed Error Handling In Bash by Willem Bogaerts, application smith at Kratz bash traps Business Solutions Summary Shell scripts are often running as background processes, doing useful things without running in a visible
Bash Script Exit On Error
shell. Think, for example, of cron jobs or scripts that are fired from a program on a web server. To write such scripts can be quite painful, as all errors occur http://linuxcommand.org/wss0150.php out of sight as well. Off course you can make use of a log file, but the ideal level of logging is hard to find. You often log way too much when the script is running fine and way too little when it unexpectedly fails. While log files can hold a lot of information, finding the relevant information is a bit trickier. https://www.howtoforge.com/detailed-error-handling-in-bash My solution is to log only the errors with all the details to a small database. This database contains tables for the message, the corresponding stack trace and the important environment variables. I have chosen for an SQLite database in this howto, but the same principle works with other databases as well. The database SQLite needs some settings to work as I expect it to, and these settings can be put in an initializing script. These settings include the error behaviour of SQLite itself and its foreign key handling: .bail ON .echo OFF PRAGMA foreign_keys = TRUE; Off course, we also need a database and I do not want to rely on one to exist. Therefore, the first thing the bash script will do is to run an SQL "revive" script on the database file: if the database did not exist, it will be created and if it did, it will do nothing: CREATE TABLE IF NOT EXISTS ErrorLog (intErrorLogId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, strMessage TEXT NOT NULL, tstOccurredAt DATE NOT NULL DEFAULT(CURRENT_TIMESTAMP) ); CREATE INDEX IF NOT EXISTS idxELOccurredAt ON Erro
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies http://unix.stackexchange.com/questions/97101/how-to-catch-an-error-in-a-linux-bash-script 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 http://phaq.phunsites.net/2010/11/22/trap-errors-exit-codes-and-line-numbers-within-a-bash-script/ 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 error handling 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? script exit on 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 add a comment| 5 Answers 5 active oldest votes up vote 4 down vote accepted Your script
to breach system security Categories Bits and Bytes (20) Editors (1) HA (10) Hacks (10) Hardware (19) HowTo's (12) Memos (3) Networking (27) Check Point (4) Cisco (6) IPv6 (2) Operating Systems (62) Debian GNU/Linux (7) DOS (2) FreeBSD (26) OS X (19) RHEL (2) Windows (8) Programming (38) Perl (12) PHP (6) RegExp (2) Scripting (13) Shells (5) TCL (1) Publications (6) Security (4) Utilities (11) Virtualization (21) jails (6) VirtualBox (5) Virtuozzo (2) VMware (4) Xen (3) Recent Tweets There are no recent tweets. November 22, 2010 Trap Errors, Exit Codes and Line Numbers within a Bash script (and some output redirection, too) Posted by: admin : Category: Programming, Scripting, Shells A discussion today was about error handling in shell scripts, Bash in particular. Well, we all know about the usual knitpicks about error handling and the possible consequences in not doing so properly 😉 The most simplistic approach in error handling are of course control structures to check the return value: some arbitrary command if [ "$?" = "0" ]; then do something else do something else fi Or even more simplistic: some arbitrary command && { do something; } || { do something else; } There are more ways to do this. But they all have in common, that it is hard to trap and trace unknown errors, especially if the script runs unattended. If you want to do some logging and tracing, then you would need to implement a routine which you would need to add to each and every block, to ensure you don't miss some particular important information. Even if it is a simple function for error reporting, let's call it error_reporter, you would end up with something like this: some arbitrary command if [ "$?" = "0" ]; then do something error_reporter args else do something else error_reporter args fi But sometimes it's better to have an error handler, which is able to catch errors and do some special actions, while still allowing your script to continue within the normal flow. Even better if that particular error handler also catches and notifies upon yet-unknown and never discovered errors. Let's assume a script, which is trying to delete a directory. For the sake of this example, the directory MUST NOT exist, so the script effectively fails upon execution. We handle the error simply by checking on the non-zero exit code. Please note: The following code serves as an example of bad script programming. Never (as in NEVER) try to delete something without checking for it's existence first! You'll find a proper code sample at the end of this article 😉 #!/bin/bash # try to delete non-existing directory # rmdir /ksdjhfskdfksh