is_defined

Function description

The is_defined function may be used to test whether a named variable has been defined, even if it currently holds a null value.

Function parameters

$1 - The name of the variable to test.

Return value

The is_defined function will return zero if the named variable is defined (even if it contains a null value) or non-zero if the named variable is undefined.

Example use

Listing 1
  1. #! /bin/bash
  2.  
  3. # We rely on some functions from hacking-bash.sh
  4. [[ -r ${HACKING_BASH_LIB_PATH:=/usr/lib/hacking-bash.sh} ]] && \
  5.     source ${HACKING_BASH_LIB_PATH} || \
  6.     { echo "Unable to find ${HACKING_BASH_LIB_PATH}"; exit 1; }
  7.  
  8. # Create some variables
  9. DEFINED_BUT_EMPTY=""
  10. DEFINED_AND_SET="hello!"
  11. unset UNDECLARED_VAR
  12.  
  13. # Test them
  14. is_defined DEFINED_BUT_EMPTY && echo "DEFINED_BUT_EMPTY is defined"
  15. is_defined DEFINED_AND_SET && echo "DEFINED_AND_SET is defined"
  16. is_defined UNDECLARED_VAR && echo "UNDECLARED_VAR is defined"
Example code demonstrating the is_defined function
max@lisa ./is_defined.sh
DEFINED_BUT_EMPTY is defined 
DEFINED_AND_SET is defined