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 Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

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