Home > Software design >  Is dictionary declared
Is dictionary declared

Time:01-17

Is there a way to check dictionary is declared in the shell?

There is a way to check variable is not empty, and there is a way to check that dictionary has a key, but not sure what is the proper way of checking that dictionary exists.

I guess I've found the solution

declare -A dictionary
dictionary[key]="val"

if [[ -z $(declare -p dictionary 2> /dev/null) ]]
then
  echo no
else
  echo yes
fi

But maybe there is a more idiomatic one?

CodePudding user response:

Multiple ways without using a sub-shell:

if declare -p dictionary 2> /dev/null
then printf 'dictionary is declared!\n'
fi

To be sure dictionary is declared and is an Associative array:

if [[ "${dictionary@a}" = *A* ]]
then printf 'dictioary is declared as an Associative array!\n'
fi

CodePudding user response:

Your declare -p trick is probably the only way to know that a variable has been marked with declare -A before anything is assigned to it (edit: Prior to Bash 5.0). The variable itself is still unset until you insert data into the array, so typical tricks using things like [[ -z ${var x} ]] won't work.

If you have Bash 5.0 or beyond, there is apparently an expansion to test for an associative array.

$ declare x; echo "${x@a}"

$ declare -a y; echo "${y@a}"
a
$ declare -A z; echo "${z@a}"
A

To check that an array has keys, you can use:

#!/bin/bash
declare -A arr1 arr2
arr1=( ["foo"]=bar )
if [[ "${!arr1[@]}" ]] ; then
  echo "arr1 has keys"
fi
if [[ "${!arr2[@]}" ]] ; then
  echo "arr2 has keys"
fi
# prints "arr1 has keys"

CodePudding user response:

I guess I've found the solution

declare -A dictionary
dictionary[key]="val"

if [[ -z $(declare -p dictionary 2> /dev/null) ]]
then
  echo no
else
  echo yes
fi

But maybe there is a more idiomatic one?

  • Related