How do I know if a variable is set in Bash?
For example, how do I check if the user gave the first parameter to a function?
function a {
# if $1 is set ?
}
How do I know if a variable is set in Bash?
For example, how do I check if the user gave the first parameter to a function?
function a {
# if $1 is set ?
}
You want to exit if it's unset
This worked for me. I wanted my script to exit with an error message if a parameter wasn't set.
This returns with an error when it's run
Check only, no exit - Empty and Unset are INVALID
Try this option if you just want to check if the value set=VALID or unset/empty=INVALID.
Or, Even short tests ;-)
Check only, no exit - Only empty is INVALID
And this is the answer to the question. Use this if you just want to check if the value set/empty=VALID or unset=INVALID.
NOTE, the "1" in "..-1}" is insignificant, it can be anything (like x)
Short tests
I dedicate this answer to @mklement0 (comments) who challenged me to answer the question accurately.
Reference http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02
In a shell you can use the
-z
operator which is True if the length of string is zero.A simple one-liner to set default
MY_VAR
if it's not set, otherwise optionally you can display the message:There are many ways to do this with the following being one of them:
This succeeds if $1 is null or unset
In bash you can use
-v
inside the[[ ]]
builtin:While most of the techniques stated here are correct, bash 4.2 supports an actual test for the presence of a variable (man bash), rather than testing the value of the variable.
Or
Or
Or