Bash Scripting Best Practices
Let’s begin with the first line of your script. The first rule always starts script with shebang. Without the shebang line, the 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 from being masked. The exit status of the last command that threw non-zero exit code is returned.
Never use backticks, use:
$( ... )
Back-ticks are visually similar to single quotes, in a larger script with hundreds of lines you could be confused if it is back-ticks or single quotes.
If you need to create temporary files, use “mktemp” for temporary files and cleanup with “trap”.