If in your bash script, you want to know if a variable is set or not you can make use of the following,
- The isset function.
- Usiing the -z option
Let's take a look at each of them with examples.
Example 1: The isset function
#!/bin/bash
isset() {
[[ -n "${!1}" ]]
}
my_var="Hey there!"
if isset "my_var"; then
echo "The variable is set."
else
echo "The variable is not set."
fi

Example 2: Using the -z Option
#!/bin/bash
if [ -z "$no" ]; then
echo "The variable is not set."
else
echo "The variable is set."
fi

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!