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

Assigning variables default values

Line 168 shows an example of providing a default value for a variable. We have already seen how to assign a value to a variable. For example:

value=$newvalue

This assigns the value of newvalue to $value. But there are times when we want to provide a default option, in case $newvalue is bogus (for example, if the user accidentally pressed <Enter> instead of entering a name). An assignment of the form variable=${value:-default} assigns value to $variable if it is set: otherwise it assigns default to $variable. In the example above, the variable ${PAGER:-more} is expanded to either the value of $PAGER, or if this is not set, to more.

For example, here is get_fname:

   94 : get_fname ()
   95 : {
   96 :   echo "Enter a filename: \c"
   97 :   read newfname
   98 :   fname=${newfname:-${fname}}
   99 : }
At the beginning of the script (we have not yet looked at this in detail) fname is set to `` '' (a space character). So if the user fails to enter a reasonable value, it remains `` ''.

There are other uses for this mechanism. For example:

   117 :   newdir=${newdir:-`pwd`}
This line sets newdir (the directory to change to) to the newly entered directory, or (if nothing is specified) to the current working directory.

Variations exist on the default behavior for a variable assignment. Some of the most common variable substitutions you can use are as follows:


${var:-word}
If var is set and not empty, substitute the value of var; otherwise substitute word.

${var:=word}
If var is not set or is empty, set it to word; then substitute the value of var (that is, if $var does not exist, set $var to $word and use that).

${var:?word}
If var is set and not empty, substitute the value of var; otherwise print word and exit from the shell.

${var:+word}
If var is set and not empty, substitute the value of word; otherwise substitute nothing.
The Korn shell provides additional substitutions for matching patterns and substituting the size of variables: see ksh(C) for details.

Next topic: Tuning script performance
Previous topic: Making menus

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003