Checking if a Bash Variable is Non-Null
There are several ways to check if a Bash variable is non-null. Let's explore the most common methods:
Using the -n
Operator
The -n
operator in Bash checks if a variable is not null (i.e., the variable has a non-empty value). Here's an example:
#!/bin/bash
my_variable="Hello, LabEx!"
if [ -n "$my_variable" ]; then
echo "my_variable is non-null."
else
echo "my_variable is null."
fi
Output:
my_variable is non-null.
In this example, the -n
operator checks if the value of my_variable
is not null, and the script prints a message accordingly.
Using the -z
Operator
The -z
operator in Bash checks if a variable is null (i.e., the variable has an empty value or is unset). This is the opposite of the -n
operator. Here's an example:
#!/bin/bash
unset my_variable
if [ -z "$my_variable" ]; then
echo "my_variable is null."
else
echo "my_variable is non-null."
fi
Output:
my_variable is null.
In this example, the -z
operator checks if the value of my_variable
is null, and the script prints a message accordingly.
Using the ${variable-default}
Syntax
Another way to check if a Bash variable is non-null is to use the ${variable-default}
syntax. This syntax returns the value of the variable if it is not null, or a default value if the variable is null. Here's an example:
#!/bin/bash
unset my_variable
echo "The value of my_variable is: ${my_variable-'default value'}"
Output:
The value of my_variable is: default value
In this example, since my_variable
is unset (i.e., null), the script uses the default value 'default value'
instead.
These are the most common methods for checking if a Bash variable is non-null. In the next section, we'll explore how to handle null values in Bash conditionals.