Bash If Error Handling
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 poor one is often measured in terms of the program's bash if error code robustness. That is, the program's ability to handle situations in which something goes wrong. Exit
Bash If Error 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 exit bash stop if error 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
Bash Check If Error
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 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 bash check if error occurred 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. 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 th
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies
Bash Script If Error
of this site About Us Learn more about Stack Overflow the company Business
Bash If Exist
Learn more about hiring developers or posting ads with us Unix & Linux Questions Tags Users Badges Unanswered Ask Question bash test exit status _ 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 http://linuxcommand.org/wss0150.php how it works: Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top How to conditionally do something if a command succeeded or failed up vote 77 down vote favorite 16 How can I do something like this in bash? if "`command` returns any error"; then echo "Returned an error" else echo "Proceed..." fi bash http://unix.stackexchange.com/questions/22726/how-to-conditionally-do-something-if-a-command-succeeded-or-failed control-flow share|improve this question edited Oct 16 '11 at 23:57 Michael Mrozek♦ 44.9k19144179 asked Oct 16 '11 at 21:25 Shinmaru migrated from programmers.stackexchange.com Oct 16 '11 at 22:29 This question came from our site for professional programmers interested in conceptual questions about software development. add a comment| 7 Answers 7 active oldest votes up vote 103 down vote That's exactly what bash's if statement does: if command ; then echo "Command succeeded" else echo "Command failed" fi Adding information from comments: you don't need to use the [ ... ] syntax in this case. [ is itself a command, very nearly equivalent to test. It's probably the most common command to use in an if, which can lead to the assumption that it's part of the shell's syntax. But if you want to test whether a command succeeded or not, use the command itself directly with if, as shown above. share|improve this answer edited Nov 23 '13 at 0:28 answered Oct 16 '11 at 21:50 Keith Thompson 8,13232235 2 Note that the semicolon is important. –Thorbjørn Ravn Andersen Oct 17 '11 at 7:37 8 Or you can just put th
this page 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 https://www.howtoforge.com/detailed-error-handling-in-bash Willem Bogaerts, application smith at Kratz Business Solutions Summary Shell scripts are often running as background processes, doing useful things without running in a visible shell. Think, for example, of cron jobs or http://www.fvue.nl/wiki/Bash:_Error_handling scripts that are fired from a program on a web server. To write such scripts can be quite painful, as all errors occur out of sight as well. Off course you can make if error 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. My solution is to log only the errors with all the details to a bash if error 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 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 NUL
error yourself if subshell fails 3.1.1 Example 1 3.1.2 Example 2 4 Caveat 2: `Exit on error' not exitting subshell on error 4.1 Solution: Use logical operators (&&, ||) within subshell 4.1.1 Example 5 Caveat 3: `Exit on error' not exitting command substition on error 5.1 Solution 1: Use logical operators (&&, ||) within command substitution 5.2 Solution 2: Enable posix mode 6 The tools 6.1 Exit on error 6.1.1 Specify `bash -e' as the shebang interpreter 6.1.1.1 Example 6.1.2 Set ERR trap to exit 6.1.2.1 Example 7 Solutions revisited: Combining the tools 7.1 Executed in subshell, trap on exit 7.1.1 Rationale 7.2 Sourced in current shell 7.2.1 Todo 7.2.2 Rationale 7.2.2.1 `Exit' trap in sourced script 7.2.2.2 `Break' trap in sourced script 7.2.2.3 Trap in function in sourced script without `errtrace' 7.2.2.4 Trap in function in sourced script with 'errtrace' 7.2.2.5 `Break' trap in function in sourced script with `errtrace' 8 Test 9 See also 10 Journal 10.1 20060524 10.2 20060525 11 Comments Problem I want to catch errors in bash script using set -e (or set -o errexit or trap ERR). What are best practices? To -e or not to to -e? Opinions differ about whether it's wise to use set -e, because of its seemingly non-intuitive problems... In favour of -e: Use set -e - Writing Robust Bash Shell Scripts - David Pashley Doubtful about -e: Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected? - BashFAQ/105 - Greg's Wiki Solutions See #Solutions revisited: Combining the tools for detailed explanations. If the script is executed in a subshell, it's relative easy: You don't have to worry about backing up and restoring shell options and shell traps, because they're automatically restored when you exit the subshell. Executed in subshell, exit on error Example script: #!/bin/bash -eu # -e: Exit immediately if a command exits with a non-zero status. # -u: Treat unset variables as an error when substituting. (false) # Caveat 1: If an error occurs in a subshell, it isn't detected (false) || false # Solution: If you want to exit, you have to detect the error yourself (false; true) || false # Caveat 2: The r