stop a script on errors
Make a script stop at the first failing command, say where, and still allow the ones that may fail.
Steps
-
set -euo pipefailat the top: stop on errors (-e), on unset variables (-u), on failing pipes
-
trap 'echo "failed at line $LINENO"' ERRsay where it stopped
-
command || { echo 'command failed'; exit 1; }stop with a message of your own
-
command || truelet this one fail
-
if command; then echo ok; fitest whether it worked: $? is its exit code
Commands used
settrap
Each has a page in lore: lore set opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.
- check if a string contains a textTest in a script whether a string contains, starts with or matches something.
- find the script's own folderInside a script, find the folder the script is in, to reach files next to it.