linux shell script how to check environment variable exist - Google Search
Scenario: You have a long command line e.g.
python sth.py --asdf $asdf --qwer $qwer --zxcv $zxcv
and you're getting the $xxxx from somewhere else.. but it could be empty..
in which case all your --xxxx get --yyyy as their arguments... not good...
linux shell script how to check environment variable exist (and define a default if it doesn't)
- 2 syntax (OLD, NEW)
http://www.cyberciti.biz/faq/bash-ksh-if-variable-is-not-defined-set-default-variable/
output=${1-text}
echo $output
Common mistake:
$output=${1-text}
If you do this, errmsg is := not defined not found etc. (becoz left hand side is blank)
Correct is this
output=${asdf-text}
or
output=${output-text}
Note, without the $ sign in front
Or, Syntax 2:
OR (see my comment below):
output=${1:-text}
echo $output
Shell Scripting: If Variable Is Not Defined, Set Default Variable
If var is defined AND NOT EMPTY, use var, otherwise set a default variable under Bash. For e.g. my script needs a parameter for output variable. It can be text or html. I set it as follows in my script
2
http://stackoverflow.com/questions/2981878/bash-checking-for-environment-variables
In Bash (and ksh and zsh), if you use double square brackets you don't need to quote variables to protect against them being null or unset.
$ if [ $xyzzy == "x" ]; then echo "True"; else echo "False"; fi
-bash: [: ==: unary operator expected
False
$ if [[ $xyzzy == "x" ]]; then echo "True"; else echo "False"; fi
False
3: useful
What's the best way to check that environment variables are set in Unix shellscript
http://stackoverflow.com/questions/307503/whats-the-best-way-to-check-that-environment-variables-are-set-in-unix-shellscr
Your question is dependent on the shell that you are using.
Bourne shell leaves very little in the way of what you're after.
BUT...
It does work, just about everywhere.
Just try and stay away from csh. It was good for the bells and whistles it added, compared the Bourne shell, but it is really creaking now. If you don't believe me, just try and separate out STDERR in csh! (-:
There are two possibilities here. The example above, namely using:
${MyVariable:=SomeDefault}
for the first time you need to refer to $MyVariable. This takes the env. var MyVariable and, if it is currently not set, assigns the value of SomeDefault to the variable for later use.
You also have the possibility of:
${MyVariable:-SomeDefault}
which just substitutes SomeDefault for the variable where you are using this construct. It doesn't assign the value SomeDefault to the variable, and the value of MyVariable will still be null after this statement is encountered.
HTH.
cheers,
Rob