Bash Check if Variable is SetA variable is often referred to as a box containing a name and the contents. A simple command, e.g., "echo Hello $Var_Name' will print "Hello...the value of the variable as defined'. Bash will print nothing if the box is empty or not created. That is why it is important to make sure whether a variable is set properly or not while creating any bash script. Variables can be categorized into two parts:
To confirm whether a variable is set or not in Bash Scripting, we can use -v var or -z ${var} options as an expression with the combination of 'if' conditional command. SyntaxFollowing are the syntaxes of boolean expression which can be used to check if the variable is set: The boolean expression returns 'True' if the variable is set and 'False' if the variable is not set. Following are the examples to check whether a variable is set or not: Using -v OptionOutput Here, variable 'A' is defined and assigned a value of 100 and hence is considered as 'set variable'. For variable 'B', we have not defined or assigned any value. As a result, the variable 'B' is not considered as 'set variable'. Using -z OptionOutput Note: There is a difference between an unset variable and a variable with a null value.Check out the following example demonstrating that the variable with a null value can be a set variable. ExampleOutput These are the commonly used methods that can be used to check if a variable is set or not. Next TopicBash Alias |