🖥 Bash scripting - set command and its usage
- In this post we will see what is set in bash scripting
- We will also discuss when to use set -e.
Set command
Use the set command to set or unset values of shell options and positional parameters. You can change the value of shell attributes and positional parameters, or display the names and values of shell variables using set command.
Set -e
sets a shell option to immediately exit if any command being run exits with a non-zero exit code. The script will return with the exit code of the failing command.
From the bash man page
set -e:
Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR > above), exits with a non-zero status.
Set -e usage
General bash script without set -e ( This script written to fail intentionaly)
#!/bin/bash
echo "a"
sleep 2
echo "b"
sleep 2
echod "c"
sleep 2
echo "d"
Script execution
kln@MacBook-Pro î‚° ~ î‚° bash check.sh
a
b
check.sh: line 9: echod: command not found
d
The above code exit code is 0. But the actual script failed in between.
kln@MacBook-Pro î‚° ~ î‚° echo $?
0
So now we will make use of set -e and see it in action
#!/bin/bash
set -e
echo "a"
sleep 2
echo "b"
sleep 2
echod "c"
sleep 2
echo "d"
kln@MacBook-Pro î‚° ~ î‚° bash check.sh
a
b
check.sh: line 9: echod: command not found
✘ kln@MacBook-Pro  ~  echo $?
127
So it’s evident that with set -e sets a shell option to immediately exit if any command being run exits with a non-zero exit code.