Substitution
Another kind of variable mangling you might want to employ is substitution. There are four substitution operators in bash, as shown in the following table.
Operator |
Function |
Example |
${foo:-bar} |
If $foo exists and is not null, return $foo. If it doesn't exist or is null, return bar. |
export foo="" echo ${foo:-one} one echo $foo |
${foo:=bar} |
If $foo exists and is not null, return $foo. If it doesn't exist or is null, set $foo to bar and return bar |
export foo="" echo ${foo:=one} one echo $foo one |
${foo:+bar} |
If $foo exists and is not null, return bar. If it doesn't exist, or is null, return a null. |
export foo="this is a test" echo ${foo:+bar} bar |
${foo:?"error message"} |
If $foo exists and is not null, return its value. If it doesn't exist or is null, print the error message. If no error message is given, print parameter null or not set. Note: In a non-interactive shell, this will abort the current script. In an interactive shell, this will just print the error message. |
export foo="one" for i in foo bar baz; do eval echo \${$foo:?} one bash: bar: parameter null or not set bash: baz: parameter null or not set |
NOTE
The colon (:) in the above operators can be omitted. Doing so changes the behavior of the operator to test only for existence of the variable. This will cause the creation of a variable in the case of ${foo=bar}.
These operators can be used in a variety of ways. A good example would be to give a default value to a variable normally read from the command-line arguments, when no such arguments are given. This is shown in the following script:
#!/bin/bash export INFILE=${1-"infile"} export OUTFILE=${2-"outfile"} cat $INFILE $OUTFILE
Hopefully, this gives you something to think about and to play with until the next article. If you're interested in more hints about bash (or other stuff I've written about), please take a look at my home page. If you've got questions or comments, please drop me a line.
Copyright © 2000, Pat Eyler
Originally published in Issue 57 of Linux Gazette, September 2000 Document available under the terms of the Open Publication License, please see http://www.linuxgazette.com/copying.html for details.