Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a variable is set in bash when using "set -o nounset"

Tags:

bash

shell

unix

The following code exits with a unbound variable error. How to fix this, while still using the set -o nounset option?

#!/bin/bash  set -o nounset  if [ ! -z ${WHATEVER} ];  then echo "yo" fi  echo "whatever" 
like image 480
vinodkone Avatar asked Oct 20 '11 06:10

vinodkone


People also ask

How do I check if a variable is set in bash?

How you can check the variable is set or not in bash is shown in this tutorial. '-v' or '-z' option is used to check the variable is set or unset. The above Boolean expression will return true if the variable is set and returns false if the variable is not set or empty.


2 Answers

#!/bin/bash  set -o nounset   VALUE=${WHATEVER:-}  if [ ! -z ${VALUE} ];  then echo "yo" fi  echo "whatever" 

In this case, VALUE ends up being an empty string if WHATEVER is not set. We're using the {parameter:-word} expansion, which you can look up in man bash under "Parameter Expansion".

like image 73
Angelom Avatar answered Sep 19 '22 23:09

Angelom


You need to quote the variables if you want to get the result you expect:

check() {     if [ -n "${WHATEVER-}" ]     then         echo 'not empty'     elif [ "${WHATEVER+defined}" = defined ]     then         echo 'empty but defined'     else         echo 'unset'     fi } 

Test:

$ unset WHATEVER $ check unset $ WHATEVER= $ check empty but defined $ WHATEVER='   ' $ check not empty 
like image 43
l0b0 Avatar answered Sep 19 '22 23:09

l0b0