|
|
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: