1

I use set -e options on top of my bash scripts to stop executing on any errors. But also I can to use -e on echo command like the following:

echo -e "Some text".

I have two questions:

  1. How to handle correctly handle errors in bash scripts?
  2. What -e options means in echo command?
2
  • -e enable interpretation of backslash escapes Commented Oct 15, 2014 at 6:19
  • 2
    set -e and echo -e have nothing to do with each other. Commented Oct 15, 2014 at 6:20

3 Answers 3

3

The "correct" way to handle bash errors depends on the situation and what you want to accomplish.

In some cases, the if statement approach that barmar describes is the best way to handle a problem.

The vagaries of set -e

set -e will silently stop a script as soon as there is an uncaught error. It will print no message. So, if you want to know why or what line caused the script to fail, you will be frustrated.

Further, as documented on Greg's FAQ, the behavior of set -e varies from one bash version to the next and can be quite surprising.

In sum, set -e has only limited uses.

A die function

In other cases, when a command fails, you want the script to exit immediately with a message. In perl, the die function provides a handy way to do this. This feature can be emulated in shell with a function:

die () {
    echo "ERROR: $*. Aborting." >&2
    exit 1
}

A call to die can then be easily attached to commands which have to succeed or else the script must be stopped. For example:

cp file1 dir/ || die "Failed to cp file1 to dir."

Here, due to the use of bash's OR control operator, ||, the die command is executed only if the command which precedes it fails.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to handle an error instead of stopping the script when it happens, use if:

if ! some_command 
then 
    # Do whatever you want here, for instance...
    echo some_command got an error
fi

echo -e is unrelated. This -e option tells the echo command to process escape sequences in its arguments. See man echo for the list of escape sequences.

1 Comment

Perhaps also note that echo -e is not portable and the OP should probably switch to using printf instead.
1

One way of handling error is to use -e in your shebang at start of your script and using a trap handler for ERR like this:

#!/bin/bash -e

errHandler () {
   d=$(date '+%D %T :: ')
   echo "$d Error, Exiting..." >&2
   # can do more things like print to a log file etc or some cleanup
   exit 1
}

trap errHandler ERR

Now this function errHandler will be called only when an error occurs in your script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.