Skip to content.

Bash opinions

Everyone has their own preferences when it comes to writing Bash scripts, I prefer very high safety & syntax consistency. A good example of both is variables, ${USER} can be shortened to $USER, but any following characters could be interpreted as part of the variable name. The longer syntax is also more powerful, enabling small conditional checks, which means we’ll likely end up using the longer syntax somewhere in our script, so why not keep it consistent and use it everywhere!

There are exceptions to everything, one inconsistency I allow for is test syntax, [ "${USER}" = "joe" ] and [[ "${USER}" = "joe" ]] have the same basic effect, but the [[ ]] syntax is more powerful, so for simple checks I prefer to use single brackets to make it clear we are looking at a simple test.

Single-line conditionals are tricky, used correctly they save clutter, used excessively and things get unreadable.

So keep them simple, run a single command in the true and one command in the false part of your if-else, example:

[ "${DEBUG}" ] && return
[ "${?}" = "0" ] && echo "Woo hoo!" || echo "Oh no.."

A good rule is to not let a single-line command or if-else wrap onto a second line in your editor..

If your conditional really has to be that long, you can continue it on a new line to avoid wrapping, example:

if [ "${UID}" = "0" ] && [ -d /proc/1/root/. ] && \
   [ "$( /usr/bin/stat -c %d:%i / )" != "$( /usr/bin/stat -c %d:%i /proc/1/root/. )" ];
then
    export IN_CHROOT="true"
fi

The same approach works for loops, example:

for path in "${HOME}/.rbenv/bin" \ 
            "${HOME}/.cargo/bin"
do
    [ -d "${path}" ] && echo "${path}"
done
avatar
Joe Heaton
Cloud HPC Engineer

Joe Heaton’s technology-focused murmurings.
comments powered by Disqus

Settings!