It's extremely important that the variables in your shell scripts are set - otherwise the results can be disastrous!
Take, for example:
$ rm -r /Users/johnPC/$UNSET_VARIABLE
# Same as rm -r /Users/JohnPC/ if variable unset!
We wouldn't want to destroy our entire home folder, would we?
Luckily there are several ways around this, with the use of substitution operators.
The following four operators are used to substitute for a variable if its value is null. Assume we have an unset variable named $TEST
.
With the dash (-
), we can simply return the value if our variable is not set.
#!/bin/bash
echo "${TEST:-hello world}"
echo "$TEST"
$ ./test
hello world
With the =
, we may set the value, and also return it.
#!/bin/bash
echo "${TEST:=hello world}"
echo "$TEST"
$ ./test
hello world
hello world
To abort the entire program if the variable is unset, use the question mark (?
).
#!/bin/bash
echo "${TEST:?hello world}"
echo "$TEST"
$ ./test
./test: line 2: TEST: hello world
We may also return a different value if the variable is set with the plus symbol (+
).
#!/bin/bash
echo "${TEST:+hello world}"
echo "$TEST"
$ ./test
Since our $TEST
variable is unset, we return nothing.
This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.
$ Check priceRelieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.
$ Check priceAd