Skip to content

How to Fix Bash Variable Unset Error

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix Bash Variable Unset Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Your Bash script fails with:

script.sh: line 5: myvar: unbound variable

Or:

script.sh: line 5: ${myvar}: parameter not set or null

This happens when you run the script with set -u (or set -o nounset) and reference a variable that has not been defined. The shell treats this as a fatal error.

Quick Fix

Step 1: Define the variable before using it

#!/bin/bash
set -u

myvar="hello"
echo $myvar  # Works

Step 2: Use default values with ${var:-default}

#!/bin/bash
set -u

# If MYVAR is not set, use "default_value"
echo "${MYVAR:-default_value}"

Step 3: Use ${var:=default} to assign a default

#!/bin/bash
set -u

# Assigns "default_value" to MYVAR if it is unset
echo "${MYVAR:=default_value}"
echo $MYVAR  # Now contains "default_value"

Step 4: Check if a variable is set

#!/bin/bash

if [ -z "${MYVAR+x}" ]; then
  echo "MYVAR is not set"
else
  echo "MYVAR is set to $MYVAR"
fi

Step 5: Temporarily disable nounset

#!/bin/bash
set -u

# Disable for one section
set +u
echo $UNDEFINED_VAR  # No error
set -u

Alternative Solutions

Use :- with positional parameters:

#!/bin/bash
# Default the first argument to "world"
echo "Hello, ${1:-world}!"

Prevention

  • Always initialize variables before using them in scripts.
  • Use set -u in development to catch undefined variables early.
  • Use set -euo pipefail for strict error checking in all scripts.
  • Document expected environment variables at the top of the script.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro