In this shot, we will learn how to check if a variable is set or not in Bash. This is useful when we want to know whether a variable is set across many files.
We can check this using the -v
option.
-v variable_name
This option takes a variable name and returns a boolean value. It returns true
if the value is set for a variable. It returns false
if the value is not set.
Let's take a look at an example of this.
x=10 #Check if the variable is set if [[ -v x ]]; then echo "variable x is already set" else echo "variable x is not set" fi
x
variable.x
is set or not using the -v
option.Note: If we execute the code snippet, it displays
variable x is already set
, as line 4 returnstrue
.
RELATED TAGS
CONTRIBUTOR
View all Courses