Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an empty array and distinguish it from an empty value in bash

Tags:

bash

I need to test if certain environment variables are set before running my script. I'm using a technique from this answer:

if  [ -z ${var1+x} ]
    echo "var1 not set"
    exit 1
fi

This works well for string variables, but there's a parameter which needs to be an array. It has to be set, but could be empty.

foo=("foo" "bar" "baz")
[ -z ${foo+x} ] # false
bar=()
[ -z ${bar+x} ] # true
[ -z ${baz+x} ] # also true

So, my question is how do I declare an empty array to make it distinct from unset variable. I'd also like to test if variable is array (whether empty or not) or non array (whether set or unset).

like image 315
Denis Sheremet Avatar asked Jan 25 '26 04:01

Denis Sheremet


2 Answers

You can use declare -p to find out what type a variable is.

scalar=1
declare -p scalar  # declare -- scalar="1"
arr=(1 2 3)
declare -p arr     # declare -a arr=([0]="1" [1]="2" [2]="3")

Undeclared variable will exit with value 1:

unset arr
declare -p arr  # bash: declare: arr: not found
echo $?         # 1

To test whether an array is empty, test ${#arr[@]}.

arr=(1 2 3)
echo ${#arr[@]}  # 3
arr=()
echo ${#arr[@]}  # 0
like image 134
choroba Avatar answered Jan 27 '26 18:01

choroba


You can use declare -p to check the variable type

$ list=()
$ declare -p list
declare -a list='()'

If the output contains "-a" your var is an array, even if empty

like image 36
franzisk Avatar answered Jan 27 '26 16:01

franzisk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!