How to check if a variable is set in Bash Script or Not


If in your bash script, you want to know if a variable is set or not you can make use of the following,

  1. The isset function.
  2. 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
    Checking if variable is set in bash

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
    Example 2 using the -z option
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap