There's a set of things every bash script should have at the top. Not "here are some nice-to-haves" — actual things that prevent real, bad, hard-to-debug failures:
#!/bin/bash set -euo pipefail IFS = $' \n\t '
Enter fullscreen mode
Exit fullscreen mode
set -e makes the script exit immediately if any command returns a non-zero status. Without it, your script keeps running after a failure and you get compounding errors that are confusing to trace.
set -u makes the script error if you reference a variable that hasn't been set. Without it, $MYVAR being undefined silently evaluates to an empty string. That empty string goes into a path. That path gets passed to rm -rf . You see where this goes.
set -o pipefail makes the exit status of a pipeline reflect the first failure in the chain, not just the last command. broken_command | grep something would exit 0 without this flag, because grep succeeded even though the input was empty.
IFS=$'\n\t' prevents word splitting on spaces in filenames.…