4 ms·
Ugh. If I have to write Bash, I try to enforce some level of basic sanity with: set -euo pipefail I've seen way too many scripts catastrophically fail be
by brobinson 10y ago
Ugh. If I have to write Bash, I try to enforce some level of basic sanity with:
set -euo pipefail
I've seen way too many scripts catastrophically fail because of unbound variables or one side of a pipe failing and the script continuing anyways, etc.
- paulddraper 10y ago+1 to this. -e Abort at the first failed line -u Abort when undefined variable is used -o pipefail Piped commands return the status of the last failed command, rather than the status of the last command
- iamdave 10y agoYou are a wonderful person for doing this. As an ops guy, I tip my hat.
- DCoder 10y agoI use the verbose version for readability: set -o errexit set -o nounset set -o pipefail Some commands need custom error handling, which means turning off -e: set +o errexit ansible-playbook ... if [[ "$?" != "0" ]]; then echo -e "\e[1;31m""Error when executing ansible!""\e[0m" exit 1 fi set -o errexit And if you use -e , you will probably need the default value helper to validate input arguments: # the :- operator means "use the right side value if the left side ($1) is not set" env=${1:-} inventoryFile="${baseDir}/env/${env}/inventory" if [[ -f "${inventoryFile}" ]]; then echo -e "\e[1;31m""Invalid environment specified!""\e[0m" exit 1 fi
- Ded7xSEoPKYNsDd 10y agoI feel your first example is better written like this: if ! ansible-playbook ... ; then echo -e "\e[1;31m""Error when executing ansible!""\e[0m" exit 1 fi But generally when I need to work around errexit, I tend to add something like " || true" or " || xyz_failed=true" to the end of the command line instead of turning it off and on again.
- user5994461 10y agoI'm mostly using ansible instead of bash noawadays. Does all the same with more commands and better error handling.
- SteveNuts 10y agoSame here, but Ansible forces a basic knowledge of Python if you want to use it really well.