UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 10.9 Shell Functions Chapter 10
Aliases
Next: 11. The Lessons of History
 

10.10 Simulated Bourne Shell Functions and Aliases

If you have a Bourne shell with no functions (10.9) or aliases (10.2), you can do a lot of the same things with shell variables and the eval (8.10) command.

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


test 



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

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

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

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

scp='
if test ! -s "$2"
then cp "$1" "$2"

else echo "scp: 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 



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

- JP


Previous: 10.9 Shell Functions UNIX Power ToolsNext: 11. The Lessons of History
10.9 Shell Functions Book Index11. The Lessons of History

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System