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

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!