bash scripting best practices

Answer

Let's begin with the first line of your script. The first rule is always starts script with shebang. Without the shebang line, system does not know which shell to process. For example:

#!/bin/bash

After shebang line write what is your script about and what it would do.

For debugging printout run your script with the "-x" or "-v" option like:

bash -x script.sh

Use the set lines:

set -e 
set -u
set -o pipefail

"-e" to immediately exit if any command has non zero exit status. "-u" causes the program to exit when you haven't previously defined variable (except $* and $@). Option "-o pipefail" prevents fails in a pipeline being masked. The exit status of last command that threw non-zero exit code is returned.

Never use backticks, use:

$( ... )

Back-ticks are visually similar to single quotes, in larger script with hundreds of lines you could be confused if it is back-ticks or single quote.

If you need to create temporary files, use "mktemp" for temporary files and cleanup with "trap".

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.