As a Linux system administrator or developer, it is crucial to be able to check if a Bash variable is set or not. There are several ways to accomplish this in Bash scripting, which I will cover in detail in this comprehensive guide.

Why Check if a Variable is Set?

Here are some common reasons you may need to check if a Bash variable is set:

  • Validate user input – Check if a variable set from user input is empty or not before using it
  • Conditional logic – Check if a variable is set before trying to use it in a script to avoid errors
  • Default values – Set a default value if a variable is not already defined
  • Error handling – Print errors and exit if required variables are not set

Knowing whether a variable has a value or not allows you to write safer Bash scripts that can handle unexpected situations gracefully.

Ways to Check if a Variable is Set in Bash

There are 5 main methods to check if a variable is set or not in a Bash script:

1. Using -v

The -v option to the [[ builtin will return true if the variable is set, even if the variable is empty:

if [[ -v VARIABLE ]]; then
  echo "VARIABLE is set"
else
  echo "VARIABLE is not set"  
fi

To also check if the variable has a non-empty value:

if [[ -v VARIABLE && -n $VARIABLE ]]; then
  echo "VARIABLE is set and not empty" 
fi

2. Using -z

The -z option will return true if the variable is unset or empty:

if [[ -z $VARIABLE ]]; then
  echo "VARIABLE is not set or is empty"  
else
  echo "VARIABLE is set"
fi

3. Parameter Expansion

Parameter expansion with ${VARIABLE+x} will substitute the default value "x" if VARIABLE is set:

result=${VARIABLE+substitute}
if [[ -n $result ]]; then
  echo "VARIABLE is set"
else
  echo "VARIABLE is not set" 
fi

4. Default Value

Set a default value to the variable to check if it was already defined:

: ${VARIABLE:=default}
if [[ $VARIABLE == "default" ]]; then
  echo "VARIABLE was not previously set"
else
  echo "VARIABLE was already set"
fi 

5. Command Substitution

Use command substitution to try and print the variable to check if it is set:

if [[ -n $(echo $VARIABLE) ]]; then
  echo "VARIABLE is set"
else 
  echo "VARIABLE is not set"
fi

The advantage of command substitution here is that it avoids issues when doing similar checks in a pipe or redirect.

Examples

Here are some examples demonstrating how to use these different methods:

1. Validate Input Variable

read -p "Enter filename: " filename

if [[ -z $filename ]]; then
  echo "Error: filename not provided" >&2
  exit 1
fi

# Rest of script uses $filename safely

This uses -z to validate the filename variable from user input is not empty before using it.

2. Check Prerequisites

if [[ -v NODEJS_HOME ]]; then
  export PATH="$NODEJS_HOME:$PATH"
else
  echo "NODEJS_HOME not set, aborting installation" >&2
  exit 1
fi

# Node.js script logic assumes $NODEJS_HOME set 

This checks if $NODEJS_HOME is set before appending it to $PATH and running Node.js scripts that rely on it being predefined.

3. Set Default Values

: ${MAXTHREADS:=10}
echo "Max threads is $MAXTHREADS"

This sets $MAXTHREADS to 10 if no value was already set.

Setting Variables Based on Other Variable Values

A common scenario is needing to set variables based on whether another variable already has a value defined or not.

Here is an example pattern to do this:

# Set default value
: ${MAXTHREADS:=10}  

# Override default if passed as argument
if [[ -v THREADS ]]; then
  MAXTHREADS=$THREADS
fi

echo "Max threads: $MAXTHREADS"

This first sets a default of 10 threads if $MAXTHREADS was not already set. Then it checks if $THREADS was passed as a command line argument, and overrides the default with that value if so.

Use this kind of pattern to implement default values that can optionally be customized.

Gotchas and Pitfalls

There are some common pitfalls when checking if variables are set in Bash:

  • Use quotes – $MYVAR vs "$MYVAR" can behave differently in [[ ]] checks
  • Works in [[ ]] but not [ ] – use [[ ]] for bash variable checks
  • -v sees assignment while -z doesn‘t – [[ -v $VAR ]] can be true even if $VAR is empty
  • Variables set and exported outside the current script can affect checks

Keep these nuances in mind as they can cause unexpected issues in Bash scripts. Use quoting properly and stick with [[ ]] over [ ] to avoid problems.

Summary

To recap, here are reliable ways to check if a variable is set in Bash:

  • [[ -v VARIABLE ]] – True if set (even if empty)
  • [[ -z $VARIABLE ]] – True if unset or empty
  • ${VARIABLE+x} – Substitutes default if set
  • : ${VAR:=default} – Sets default if not already set
  • [[ -n $(echo $VAR) ]] – Command substitution print test

And examples:

  • Validate variables from input before use
  • Check prerequisites like directories before script logic
  • Implement default values that can be optionally customized

Understanding these methods along with their caveats gives you the knowledge to reliably test variables in your Bash scripts. This helps handle errors gracefully and write safer Bash code.

Let me know in the comments if you have any other tips or gotchas when evaluating if variables are set in Bash!

Similar Posts