Bash Idioms For Portability

The life of one of your Bash scripts is hard to reckon when you first write it. They often end up at opposite ends of the company on very different systems. This makes it a good idea to make them as portable as possible.

A couple of easy wins here are to replace the traditional interpreter line and drop echo commands.

Script Interpreter

The traditional interpreter line at the start of the file usually links to the binary of the shell that you want the script to get executed by. E.g. for Bash

#! /usr/bin/bash

Unfortunately the Bash binary can be stored in different locations on different distros so this can fail. Replace this line with the env command for an easy win. env has access to the local environment variables such as the location of interpreters and is always in the same location.

Here it is for Bash:

#! /usr/bin/env bash

And for Python3:

#! /usr/bin/env python3

Using this as your interpreter line will avoid lots of issues down the line.

echo v printf

The echo command behaves somewhat differently on different distros so much that it can cause some scripts to fail or behave unexpectedly. In place of echo use printf.

The only unexpected part of using printf is that you need to specify all new lines. The following echo statement:

echo "Hello World!"

Becomes the following printf statement:

printf "Hello World!\n"

It’s not much extra work and will save you time in the future working out why your script has failed on some distant system.