NASutils Knowledge BaseUnofficialPolski

Bash · lesson 20 of 30 · Files and errorsStop at the first error

-e ends the script at a failed command, -u at a variable without a value, and pipefail counts a failure anywhere in a pipe. trap ERR names the command.

Programming on the NAS › Bash in 30 lessons

20-strict.sh Download 20-strict.sh

#!/usr/app/TurboShell/bin/bash
# -e ends the script at a failed command, -u at an unset name,
# pipefail counts a failure anywhere in a pipe
set -euo pipefail
trap 'echo "stopped at: $BASH_COMMAND"' ERR

echo "copying"
cp words.txt safe.txt
echo "copying a file that is not there"
cp missing.txt safe2.txt
echo "this line never runs"

Terminal

$ bash 20-strict.sh 2>/dev/null; echo "exit code $?"
copying
copying a file that is not there
stopped at: cp missing.txt safe2.txt
exit code 1

Exercise

Let one command fail on purpose with || true.