Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an associative array element exists in my Bash script?

Tags:

bash

I have an array of animals:

declare -A animals=()
animals+=([horse])

and I want to check if an animal exists or not:

if [ -z "$animals[horse]"]; then
    echo "horse exists";
fi

but this does not work.

like image 731
sensorario Avatar asked Jun 10 '15 07:06

sensorario


People also ask

Does bash have associative arrays?

Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values.

What is associative array in bash?

3 years ago. An array variable is used to store multiple data with index and the value of each array element is accessed by the corresponding index value of that element. The array that can store string value as an index or key is called associative array.

What is the command to create an associative array in bash?

An associative array in bash is declared by using the declare -A command (How surprising, I know :D). The variable inside the brackets - [] will be the KEY and the value after the equal sign will be the VALUE. We'll use Countries as KEYS and Capitals as VALUES.

How do you check if a string is present in an array in shell script?

Here is a small contribution : array=(word "two words" words) search_string="two" match=$(echo "${array[@]:0}" | grep -o $search_string) [[ ! -z $match ]] && echo "found !" Note: this way doesn't distinguish the case "two words" but this is not required in the question.


1 Answers

In bash 4.3, the -v operator can be applied to arrays.

declare -A animals
animals[horse]=neigh
# Fish are silent
animals[fish]=
[[ -v animals[horse] ]] && echo "horse exists"
[[ -v animals[fish] ]] && echo "fish exists"
[[ -v animals[unicorn] ]] || echo "unicorn does not exist" 

In prior versions, you would need to be more careful distinguishing between the key not existing and the key referring to any empty string.

animal_exists () {
    # If the given key maps to a non-empty string (-n), the
    # key obviously exists. Otherwise, we need to check if
    # the special expansion produces an empty string or an
    # arbitrary non-empty string.
    [[ -n ${animals[$1]} || -z ${animals[$1]-foo} ]]
}

animal_exists horse && echo "horse exists"
animal_exists fish && echo "fish exists"
animal_exists unicorn || echo "unicorn does not exist"
like image 60
chepner Avatar answered Sep 21 '22 02:09

chepner