DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

Context sensitive scripts

Some programs, for example ls, have many options. Rather than require users to always specify the commonest options, ls has a number of links (alternative names). When you run ls it examines the parameter $0, which contains the name under which it was invoked, and uses the appropriate options. For example, l is equivalent to ls -l; lc is equivalent to ls -c, and so on.

Your scripts can behave the same way. For example:

   # should check number and type of args here
   case `basename $0` in
   add) 	expr $1 + $2
           ;;
   subtract) expr $1 - $2
           ;;
   multiply) expr $1 \* $2
           ;;
   divide) expr $1 / $2
           ;;
   *)
           echo "Unknown operation: $0" >&2
           exit 1
           ;;
   esac
   exit
This short script has four names; it can be invoked as add, subtract, multiply and divide. It takes two arguments, and evaluates them according to the name under which it was invoked. basename is used to remove any preceding path (which might prevent the case statement from matching anything). For example:
   $ add 5 4
   9
   $ subtract 4 5
   -1
   $
The variable $0 contains the name under which the script was invoked. By using links to the script (rather than four separate script files) we conserve the number of files needed. In addition, if it is necessary to alter the behavior of all the programs, you can alter just the core file and the change will be recognized by all the links to it.

As an alternative, we could write an application that used several command line tools to update a database, all of which were links to a single tool that behaved differently depending on the context in which it was invoked.


Previous topic: Locking files

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005