Monday, July 27, 2015

Failing fast in bash scripts

If you want your bash script to stop execution as soon as any of the commands returns a non-zero exit status, invoke bash with the -e option.
For example, the following script will continue to run, even though the sub-shell exited with the status 1.
1
2
3
#!/bin/bash 
exit 1 )
echo "This will be echoed"
However, if the script invokes bash with the -e option, the script ends as soon as the subshell returns 1.
1
2
3
#!/bin/bash -e
exit 1 )
echo "This will not be echoed"
Note: Although I’ve used the subshell as an example here, but the script will stop executing for any command failure e.g. wget, curl, etc.

No comments: