Unix shell code that is portable enough to run on all shells Unix shell code that is portable enough to run on all shells shell shell

Unix shell code that is portable enough to run on all shells


Get yourself a 7th Edition Unix Programmer's Manual (Vol 1) and program to the (Bourne) shell notation described there. You can actually upgrade to a System V (Bourne) shell if you can find an appropriate manual; it has a few extra features, like functions, that the 7th Edition shell did not have, and they are essentially available everywhere. (This is a very conservative stance - but it will give you maximal portability.)

The other issue is choosing which commands you use, and which options you use to those commands. For example, GNU grep has numerous useful options that are not available elsewhere. GNU sed similarly has extensions that are not available elsewhere. If you write your shell script to use those extensions, your code will be unportable, even if the shells all understand the syntax correctly.

I recommend being aware of what the POSIX standard says is portable. Most of the POSIX features are usually supported by most systems, but each system usually adds some extra options and features that are not always widely available. Note that the POSIX shell does have some features, notably $(...) command substitution in place of back-ticks that you were not in original Bourne shells. You'll have to decide whether the clarity that the more modern notation brings is worth the (nominal) loss of portability.

Also, the Autoconf shell guidelines concentrate on maximal portability. However, the result is a rather stilted version of shell scripting, not least because it has to interwork with the m4 macro processor, which leads to some additional constraints.


Note that it is essentially impossible to write portable shell scripts that will work with the Bourne/Korn/POSIX shell family and the C Shell family. There are strong arguments for concluding "you should not write scripts in C shell".


The short answer for portability is to write scripts for the lowest common denominator which is the Bourne shell (sh) and to avoid C shell which has an incompatible syntax and serious limitations. The Bourne shell should be universally available and most system startup and administration scripts are written for it.

All of the capabilities you mentioned as requirements are available in sh. One of the main things that is missing is support for arrays, but that can be worked around.

One thing to keep in mind is that much of the functionality of a shell script is provided by external utilities which are accessible from any shell.


why not write your scripts in perl or python?