Bash Exception Error Handling
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
Bash Error Handling Best Practices
Stack Overflow the company Business Learn more about hiring developers or posting ads with error handling in bash shell script us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is
Linux Bash Error Handling
a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Error handling in BASH up vote 143 down vote favorite 110 What is bash catch exception your favorite method to handle errors in BASH? The best example of handling errors in BASH I have found on the web was written by William Shotts, Jr at http://www.linuxcommand.org. William Shotts, Jr suggests using the following function for error handling in BASH: #!/bin/bash # A slicker error handling routine # I put a variable in my scripts named PROGNAME which # holds the name of the program being run. bash throw error You can get this # value from the first item on the command line ($0). # Reference: This was copied from
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and
Bash Traps
policies of this site About Us Learn more about Stack Overflow the bash catch error message company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags
Bash Error Code
Users Badges Ask Question 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; it only http://stackoverflow.com/questions/64786/error-handling-in-bash takes a minute: Sign up Exception handling in shell scripting? up vote 43 down vote favorite 14 I'm looking for exception handling mechanism in shell script. Is there any try,catch equivalent mechanism in shell script ? bash shell exception-handling share|improve this question edited Oct 23 '13 at 3:30 asked Aug 5 '11 at 19:06 Mandar Pande 3,03693055 Related: Could http://stackoverflow.com/questions/6961389/exception-handling-in-shell-scripting someone explain this try/catch alternative in bash? –blong Apr 11 '14 at 12:54 add a comment| 4 Answers 4 active oldest votes up vote 62 down vote accepted There is not really a try/catch in bash (i assume you're using bash), but you can achieve a quite similar behaviour using && or ||. In this example, you want to run fallback_command if a_command fails (returns a non-zero value): a_command || fallback_command And in this example, you want to execute second_command if a_command is successful (returns 0): a_command && second_command They can easily be mixed together by using a subshell, for example, the following command will execute a_command, if it succeeds it will then run other_command, but if a_command or other_command fails, fallback_command will be executed: (a_command && other_command) || fallback_command share|improve this answer edited Dec 28 '13 at 13:04 answered Aug 5 '11 at 19:13 MatToufoutu 8,9314451 8 Bonus: if you want "finally" like behavior, use the no-op (: in bash) like this: (a_command || : ) and the next line will run as if no error happened in a_command.
Detailed Error Handling In Bash Summary The database The mechanism Caveat Invoking the error handler The full script Usage example References Detailed Error Handling In Bash by Willem Bogaerts, application smith at Kratz Business Solutions Summary Shell scripts https://www.howtoforge.com/detailed-error-handling-in-bash are often running as background processes, doing useful things without running in a visible shell. Think, for example, of cron jobs or scripts that are fired from a program on a web server. To write such scripts can http://bioinfornatics.eu/blog/2013/06/30/programming/how-to-handle-error-from-your-bash-workflow/ be quite painful, as all errors occur 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 error handling 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. 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 bash error handling 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 ErrorLog(tstOccurredAt); CREATE TABLE IF NOT EXISTS ErrorStackTrace (intErrorStackTraceId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, intErrorLogId INTEGER NOT NULL, strSourceFile TEXT NOT NULL, strFunction TEXT NOT NULL, intLine INTEGER NOT NULL, FOREIGN KEY(intErrorLogId) REFERENCES ErrorLog(intErrorLogId) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE INDEX IF NOT EXISTS idxESTTraceErrorLogId ON ErrorStackTrace(intErrorLogId); CREATE TABLE IF NOT EXISTS ErrorEnvironment (intErrorEnvironmentId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, intErrorLogId INTEGER NOT NULL, strVariable TEXT NOT NULL, strValue TEXT NULL, FOREIGN KEY(intErrorLogId) REFERENCES ErrorLog(intErrorLogId) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE INDEX IF NOT EXISTS idxEEErrorLogId ON ErrorEnv
all that is the job to a command line interpreter! Often i see perl script which use mainly system function. That is a nonsense, take the script change .pl to .sh, remove system and you have mostly a bash script. The problem Most of people think to know bash but finally they do not know it well. Is so easy to run a command in bash … How to handle errors? That is the job to trap ! trap is a built-in really powerful for this purpose # die # This function is used to raise an error # Parameters: # - line number # - message # - exit code (optional) die () { local parent_lineno message code parent_lineno="$1" message="$2" [[ -n $3 ]] && code="$3" || code=1 if [[ -n "$message" ]] ; then echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}" >&2 else echo "Error on or near line ${parent_lineno}; exiting with status ${code}" >&2 fi end "${code}" } ## MAIN trap 'die ${LINENO}' 1 15 ERR ls $RANDOM echo 'I am here' What we do: at line 6-19 we declare the die function at line 21 we tell to bash to call die function if process exit with a signal ERR, 1 or 15 at line 22 we try to list a file who has the name given by $RANDOM . I assume this file do not exist line 23 is never call unless you have a file who has the name than the random number given by $RANDOM Customize the error message Some time you would like to give a specific message. that is possible, look this … ls $RANDOM || die 'File unknown' 1 If ls fail it will call die function with the specific message and finally script exit with code 1. Make stronger bash functions With the same code you can does something close to contract programming. … foo(){ [[ $# -eq 2 ]] || die 'foo function need two parameters: first name, last name' [[ -s "$1" ]] || die 'first name should not to be empty' [[ -s "$2" ]] || die 'last name should not to be empty' echo "hello $1 $2" } As you can to see using die function with trap built-in will enhance your bash script. The command built-in To continue on the same topic they are a built-in little known. That is command. Looking some help for this built-in with your favourite search engine is mostly impossible as command is too generic keywords. This built-in will run for you external program and i