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

portability, shell, unix

Solution

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".

Problem

Can anyone please let me know the coding guidelines along with code samples of Unix shell scripting by using which the code can run on most of the current shells like ksh, bash, csh etc. Most of the times some of my code written for ksh would not work on normal sh. I want to make my code maximum portable. Most of my code will be around [ifs, elifs] and [whiles, fors] and return code capturing of child shell (which will mostly be running SQL scripts for which I want to get some of the return codes like number of rows processed, return codes, error codes of the SQL script). Also can anyone let me know which shell specific code can be easily ported to other shells? Can anyone point me to right tutorials and/or sample codes?

Original source