Skip to content

Bash best practices

Bash is huge and there are already some great resources on it.

So this is a concise list of the most important practices to me in Bash.

Prefer while over for when looping over command output

while read -r line; do
  echo "$line"
done < <(command)

Don't use capitalized variable names

Write bash just like any other scripting language, no need to capitalize all your variable names because they might clash with environment variables.

Never parse ls

This is a widely held practice by now because ls outputs filenames and filenames can contain all sorts of crazy unprintable characters according to POSIX standards.

Learn glob behaviour

You can modify file glob behaviour with shopt to some extent. Perhaps as an alternative to something you'd do with ls.

Reset LANG environment variables in scripts

Not all scripts but if you're parsing command output in your script and you want it to work on other computers then I suggest doing this. Because localized Linux installs might output a different text and break your parsing.

Use $() instead of backticks ``

For command substitution, because ''$()'' nests easier and is clearer to read imo.

Prefer single quoted strings

To avoid issues I always prefer single quoted strings and only whip out the double quotes if I absolutely need them.

Parameter expansion is great

You can do so many things with it.

See also


Last update: September 19, 2021