Developing Portable Shell Scripts

Problem

You are writing a shell script that will need to run on multiple versions of multiple Unix or POSIX operating systems.

Solution

First, try using the command built-in with its -p option to find the POSIX version of program, e.g., in /usr/xpg4 or /usr/xpg6 on Solaris:

$ command -p program args

Then, if possible, find the oldest or least capable Unix machine and develop the script on that platform. If you aren’t sure what the least capable platform is, use a BSD variant or Solaris (and the older a version you can find, the better).

Discussion

command -p uses a default path that is guaranteed to find all of the POSIX-standard utilities. If you’re sure your script will only ever run on Linux (famous last words), then don’t worry about it;otherwise, avoid developing cross-platform scripts on Linux or Windows (e.g., via Cygwin).

The problems with writing cross-platform shell scripts on Linux are:

  1. /bin/sh is not the Bourne shell, it’s really /bin/bash in Bourne mode, except when it’s /bin/dash (for example Ubuntu 6.10). Both are very good, but not perfect, and none of the three work exactly the same, which can be very confusing. In particular, the behavior of echo can change.

  2. Linux uses the GNU tools instead of the original Unix tools.

Don’t get us wrong, we love Linux and use it every day. But it isn’t really Unix: it does some things differently, and it has the GNU tools. The GNU tools are great, and that’s the problem. They have a lot of switches and features ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.