home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Unix Power ToolsUnix Power ToolsSearch this book

29.14. Simulated Bourne Shell Functions and Aliases

Until System V Release 2 (circa 1984), the Bourne shell had no way for users to set up their own built-in commands. If you have a Bourne shell with no functions (Section 29.11) or aliases (Section 29.2) and haven't yet turned the host machine into a wet bar, CD/DVD storage case, or some other pragmatic but fun use for a 30-year-old computer, you can do a lot of the same things with shell variables and the eval (Section 27.8) command.

Let's look at an example. First, here's a shell function named cps (copy safely). If the destination file exists and isn't empty, the function prints an error message instead of copying:

test Section 35.26

cps( )
{
   if test ! -s "$2"
   then cp "$1" "$2"
   else echo "cps: cannot copy $1: $2 exists"
   fi
}

If you use the same cps twice, the first time you'll make bfile. The second time you try, you see the error:

$ cps afile bfile
   ...
$ cps afile bfile
cps: cannot copy afile: bfile exists

Here's the same cps -- stored in a shell variable instead of a function:

cps='
if test ! -s "$2"
then cp "$1" "$2"
else echo "cps: cannot copy $1: $2 exists"
fi
'

Because this fake function uses shell parameters, you have to add an extra step: setting the parameters. Simpler functions are easier to use:

set Section 35.25

$ set afile bfile
$ eval "$cps"
   ...
$ eval "$cps"
cps: cannot copy afile: bfile exists

-- JP



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.