1

In a bash script what is the use of

set -e

?

I expect it has something to do with environment variables but I have not come across it before

IanWatson
  • 1,649
  • 2
  • 27
  • 49

3 Answers3

3

quoting from help set

  -e  Exit immediately if a command exits with a non-zero status.

i.e the script or shell would exit as soon as it encounters any command that exited with a non-0(failure) exit code.

Any command that fails would result in the shell exiting immediately.

As an example:

Open up a terminal and type the following:

$ set -e
$ grep abcd <<< "abc"

As soon you hit enter after grep command, the shell exits because grep exited with a non-0 status i.e it couldn't find regex abcd in text abc

Note: to unset this behavior use set +e.

riteshtch
  • 8,629
  • 4
  • 25
  • 38
1

man bash says

Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ││ list, or if the command’s return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits.

It is super convenient way to get "fail-fast" behaviour if you want to avoid testing the return code of every command in a bash script.

AnoE
  • 8,048
  • 1
  • 21
  • 36
0

Suppose there is no file named trumpet in the current directory below script :

#!/bin/bash
# demonstrates set -e
# set -e means exit immediately if a command exited with a non zero status

set -e 
ls trumpet #no such file so $? is non-zero, hence the script aborts here
# you still get ls: cannot access trumpet: No such file or directory
echo "some other stuff" # will never be executed.

You may also combine the e with the x option like set -ex where :

-x Print commands and their arguments as they are executed.

This may help you debugging bash scripts.

Reference:Set Manpage

sjsam
  • 21,411
  • 5
  • 55
  • 102