The wonderful world of bash scripting

Currently this is a list of tools and practices I fancy related to programming in bash. Naturally this list will change. In the end this should give beginners a nice overview and serve as my personal reference list as it reflects my current personal opinion.

Remember: I am not telling you how to run your life, I am just saying that it will be easier that way. So take “should” and “want” with a grain of salt, as always.

What you should do NOW!! (see also: “The light at the end of the tunnel of horrible quirks”)

  • use shellcheck. use a (static) code analysis tool (like you do for any other programming language, right?) shellcheck to the rescue (GitHub)
  • use set -e and set -u. these switches make Bash's behaviour a little bit … nicer (perl programmers already know this :)). And use set -x and set +x for debugging
  • use printf instead of echo. Variable substitution VAR=$(printf "foobar%s" "$foo") instead of concatenation, or this: VAR="foobar${foo}"
  • use the local keyword in functions
  • use test

Template

A good starting point, together with local and shellcheck is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/env bash

set -e
set -u

SCRIPTPATH=$( cd "$(dirname "$0")" ; pwd -P )
test -n "$SCRIPTPATH" | printf "\$SCRIPTPATH not set!\n"
printf "Your script is here: %s\n" "$SCRIPTPATH"

exit 0

Reading/Traversing

while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
done < "$1"
  • traverse files in a directory: find DIR -name NAME -print0 | xargs -0 so for loops won't break on spaces
  • build paths from absolute values and not from the current directory, see SCRIPTPATH and e.g. HOME

Substring Manipulation

Working with substrings: - extraction: ${string:position} and ${string:position:length} - removal: ${string#substring} and ${string##substring} - replacement: ${string/substring/replacement} and ${string//substring/replacement}

Robustness