Shell Script Portability Hints (or so much for POSIX)

The first rule is to never assume anything is where you think it is, /usr/bin/env is your friend, especially in combination with #!

Use commands in preference to environment variables, although it’s nice that environment variables like $PWD and $USER maybe set they aren’t always what you are looking for. For instance on FreeBSD if you are in your home directory, $PWD will probably read /home/user_name, but if you want the absolute path you should use $(pwd -P) or $(/bin/pwd)  (shell built-in vs command) which will yield /usr/home/user_name, two very different results. On Solaris $USER isn’t set, you need to use $LOGNAME instead or better $(/usr/ucb/whoami)

I’m not sure why the command line double-dash option, for example”–something” came into being, but it is not very portable when it comes to basic UNIX commands like “ln”, “tar”, or anything else for that matter, always use the short form for your scripts,  so “ln -s -f” instead of “ln -s –force”

Use indirection, create your own set of environment variables/functions that have the correct platform dependent references set upon initialization and then you can change your platform without modifying your main scripts. Your script may be a little uglier but it will run much better.

Pipelining is still your friend, many commands like tar have shortcuts to avoid piplining for instance “tar zxf” to automatically decompress the file before untaring it, nice and easy to write but not very portable. Instead use the long form “gzcat filename | tar xf – “, also you will probably need to “cd dirname” to your directory instead of using “-C  dirname” which isn’t supported on all platforms.

For cross platform testing (if you care about such things or need to worry about it) get yourself a copy of VMWare and set up your target test environments and start testing as destructively as you like, this beats dual booting or running multiple machines, you can have one virtual QA environment setup, VMWare Server is particularly good for this.

Leave a Reply