Menu

1 / 2

Every bash script I write starts with the same 20 lines. So I made a generator for them.

DEV Community·Anguishe·6 months ago
#o58Gk8i9
#bash#linux#devops#webdev#script
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.