You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
10.3.3. Transformations of variables<br />
<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />
10.3.3.1. Substitution<br />
${VAR:-WORD}<br />
If VAR is not defined or null, the expansion of WORD is substituted; otherwise the value of VAR is substituted:<br />
[bob in ~] echo ${TEST:-test}<br />
test<br />
[bob in ~] echo $TEST<br />
[bob in ~] export TEST=a_string<br />
[bob in ~] echo ${TEST:-test}<br />
a_string<br />
[bob in ~] echo ${TEST2:-$TEST}<br />
a_string<br />
This form is often used in conditional tests, for instance in this one:<br />
[ -z "${COLUMNS:-}" ] && COLUMNS=80<br />
It is a shorter notation for<br />
if [ -z "${COLUMNS:-}" ]; then<br />
COLUMNS=80<br />
fi<br />
See Section 7.1.2.3 for more information about this type of condition testing.<br />
If the hyphen (-) is replaced with the equal sign (=), the value is assigned to the parameter if it does not exist:<br />
[bob in ~] echo $TEST2<br />
[bob in ~] echo ${TEST2:=$TEST}<br />
a_string<br />
[bob in ~] echo $TEST2<br />
a_string<br />
The following syntax tests the existence of a variable. If it is not set, the expansion of WORD is printed to<br />
standard out and non-interactive shells quit. A demonstration:<br />
[bob in ~] cat vartest.sh<br />
#!/bin/bash<br />
# This script tests whether a variable is set. If not,<br />
# it exits printing a message.<br />
echo ${TESTVAR:?"There's so much I still wanted to do..."}<br />
echo "TESTVAR is set, we can proceed."<br />
[bob in testdir] ./vartest.sh<br />
./vartest.sh: line 6: TESTVAR: There's so much I still wanted to do...<br />
Chapter 10. More on variables 127