Bash Set

March 21, 2018

I wasn't aware of using set in a bash script until I came across it today.

Stop script if command fails

You can use it to stop a bash script as soon as a script returns a non zero (ie not success) result, with the -e flag.

Given the following test.py file:

print "In Python"
exit(1)

and this bash script:

#!/bin/bash
set -e

ls
echo "calling python" 
python test.py
echo "done"

Running this script will output:

test    test.py
calling python
In Python

The script stops at the python command. Changing the python to do exit(0) means the script completes normally.

Echo Commands

The set -x option allows you to output the line that is running before it is executed. So, given the above python program and bash script (with the -e changed to -x), the following it output:

+ ls
test    test.py 
+ echo 'calling python'
calling python 
+ python test.py
In Python 
+ echo done
done

References

Tags: bash set script