By default, a script goes on after a command fails, and ends saying it worked:
text
learner@reef:~$ ./copy-menu.sh
copying the menu
cp: cannot stat '/home/learner/menu.txt': No such file or directory
menu copied ← it wasn't
learner@reef:~$ echo $?
0 ← and it says it workedOne line under the shebang makes it stop instead:
bash
#!/bin/bash
set -euo pipefail| Part | Stops the script at |
|---|---|
-e | a command that fails |
-u | a variable that was never set: shpo: unbound variable |
-o pipefail | a pipe in which any command fails. Without it, only the last command's exit code counts |
Where -e does not stop
-e doesn't stop for a failure the script tests:
| Line | Stops when cp fails? |
|---|---|
cp a b | Yes |
if cp a b; then | No: it's the test |
cp a b && echo "copied" | No |
cp a b || exit 1 | No: you handled it |