.oO  |  List directory  |  History  |  Similar  |  Print version
Projects 
   ScummC 
   php edna 
   nixshare 
   concede 
   Orewar 
   AEval 
Portable Coding 
   Shell scripts 
   Standard C 
Random stuff 
   Slackware and UTF-8 
   Bit tricks 
Wiki 
   Links 
   Playground 
   Impressum 

Portable Coding > Shell scripts

 
rw-rw-r--   albeu   portable
Table of contents:

Shell scripts

Really portable shell scripts are a nigthmare if one want to do anything complex. So the KISS rules apply all more then ever ;)

Commands

Using the not operator ! on a command is NOT portable. So don't do:

if ! grep foo file ; then
  bar
fi

an alternative is:

grep foo file
if [ $? -ne 0 ] ; then
  bar
fi

Tests

You can use [ ] and test, test is rumored to be more portable but I couldn't find a system where [ ] doesn't work yet. However on some systems (solaris) the shell builtin test is very limited compared to /bin/test (no file test). So if [ ] is used then one is stuck with the builtin where test can simply be overrided with a function.

The && and || operators inside tests are not portable. So don't do:

if [ $? -eq 0 && "$foo" = "bar" ] ; then

but something like:

if [ $? -eq 0 ] && [ "$foo" = "bar" ] ; then

or

if test $? -eq 0 -a "$foo" = "bar" ; then

Functions

Only use foo() { } to define functions, the function keyword is not portable.

Text utils

grep -q foo is sadly not portable, use something like grep foo 2> /dev/null >&2 instead.

The character classes (like [:alpha:],[:alnum:],etc) are missing on some grep and sed (solaris again).

head and tail are a bit tricky. Newer version want head -n 1 but older requiere head -1. Hence one need to use some function. From MPlayer configure:

if test "`(echo line1 ; echo line2) | head -1 2>/dev/null`" = "line1" ; then
  _head() { head -$1 2>/dev/null ; }
else
  _head() { head -n $1 2>/dev/null ; }
fi


Reference http://alban.dotsec.net/PortableCoding/ShellScripts

Comments: 0 New comment

Prev. Portable Coding Tips 'n Tricks   Standard C Next