Failed commands do not stop script execution

suggest change

In most scripting languages, if a function call fails, it may throw an exception and stop execution of the program. Bash commands do not have exceptions, but they do have exit codes. A non-zero exit code signals failure, however, a non-zero exit code will not stop execution of the program.

This can lead to dangerous (although admittedly contrived) situations like so:

#!/bin/bash
cd ~/non/existent/directory
rm -rf *

If cd-ing to this directory fails, Bash will ignore the failure and move onto the next command, wiping clean the directory from where you ran the script.

The best way to deal with this problem is to make use of the set command:

#!/bin/bash
set -e
cd ~/non/existent/directory
rm -rf *

set -e tells Bash to exit the script immediately if any command returns a non-zero status.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents