Unix Shell Scripting Standards

Would anyone have details of pre-existing Unix shell scripting standards. I've been asked to prepare a document outlining standards when writing korn shell scripts & don't really know where to start. Thanks.

Below are a couple of rules to get you started. Good luck with it...

All scripts will begin with #!/bin/ksh to ensure we get ksh results however script is invoked.

All scripts requiring input parameters will contain code to ensure the user has entered an appropriate number of parameters, else the script will display a proper syntax message explaining correct use of the command.

All scripts which create temporary files will create these files in the /tmp directory with the process id as part of the data set name (i.e. /tmp/$$.somename), and will employ the trap command to cleanup all /tmp files on completion, example here:

trap "rm -f /tmp/$$.* 2>/dev/null; exit 2" 1 2 3 9 15
trap "rm -f /tmp/$$.* 2>/dev/null; exit 0" 0

All scripts requiring SAS code to be generated, will use the << functionality to generate the required SAS code dynamically into a /tmp data set.

The Korn shell will run all scripts that conform to the POSIX standard for the shell. By writing scripts that conform to the standard, you will also be able to run them with other shells if that should ever be needed.

For more information see the standard at Shell & Utilities: Table of Contents.

Thanks a million 66IISW & cfajohnson for your replies, I will try & use the information you've sent on.

It will not get ksh results if ksh is not in /bin.

It will not get ksh results if it is started with:

sh /path/to script

Or (if your shell isn't ksh):

. /path/to script

It may not work if the ksh in /bin is pdksh and you need ksh93.

It will probably work if /bin/ksh is a link to zsh. This is common on a lot of our Linux boxes here.

What CFA J & I are telling you is that the best practice is to use the magic at the top of your script. But you do not have guarantees what shell you will invoke, especially when the code is ported. So, on the internet, that becomes very true - like porting into a black hole. So, #!/bin/ksh may not mean what you think.

Consider reading the link in the above post if you're confused about standards.

On most Linux distros I've used, /bin/ksh is pdksh, which differs from the standard AT&T ksh in some important respects.

Actually, I am not saying that. A shebang is usually unnecessary, and reduces the portablility of a script.