Source From Here
Question
How do I know if a variable is set in bash?
How-To
The following solution is incorrect:
The execution will told you the VAR is unset which is wrong:
This is because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if var='', then the above solution will incorrectly output that var is unset.
But this distinction is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
where
${VAR+x} is a parameter expansion which evaluates to the null if VAR is unset and substitutes the string "x" otherwise. For example:
Supplement
* Linux and Unix test command
Question
How do I know if a variable is set in bash?
How-To
The following solution is incorrect:
- #!/bin/bash
- export VAR=''
- function checkVar {
- if [ -z "$VAR" ]; then
- echo "VAR is unset!"
- else
- echo "VAR is set to '$VAR'"
- fi
- }
- echo "VAR is '$VAR'"
- checkVar
This is because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if var='', then the above solution will incorrectly output that var is unset.
But this distinction is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
- function checkVar2 {
- if [ -z ${VAR+x} ]; then
- echo "VAR is unset"
- else
- echo "VAR is set to '$VAR'"
- fi
- }
Supplement
* Linux and Unix test command
沒有留言:
張貼留言