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”)
shellcheck. use a (static) code analysis tool (like you do for any other programming language, right?) shellcheck to the rescue (GitHub)
set -u. these switches make Bash's behaviour a little bit … nicer (perl programmers already know this :)). And use
set +xfor debugging
echo. Variable substitution
VAR=$(printf "foobar%s" "$foo")instead of concatenation, or this:
- use the
localkeyword in functions
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 lines of a file (Source: https://stackoverflow.com/a/10929511):
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 -0so for loops won't break on spaces
- build paths from absolute values and not from the current directory, see SCRIPTPATH and e.g. HOME
Working with substrings: