CarstenP
CarstenP

Reputation: 241

Bash 4+: Checking whether a key-value-pair within an assoc array has been set

I want to check whether a certain key-value-pair within an associative array in a Bash script has been set or not.

My code so far (example only):

#!/bin/bash

declare -A aa
aa[FIRST[SECOND]]=1

if [ ! -z ${aa[FIRST[SECOND]]+x} ]; then
    echo "Yes, value is ${aa[FIRST[SECOND]]}."
else
    echo "No, the item has not been set yet."
fi

To me this seems save and sound, but before submitting pivotal scripts to a core community elsewhere I thought it'd be a good idea to ask the cracks.

Upvotes: 0

Views: 65

Answers (2)

bogomips
bogomips

Reputation: 21

Just a bit shorter :)

 if [[ ${aa[FIRST[SECOND]]+x} ]]; then ...

i.e. assuming key to be a string "FIRST[SECOND]"

Upvotes: 1

chepner
chepner

Reputation: 531275

Starting in bash 4.3, you can use the -v operator.

if [ -v aa[FIRST[SECOND]] ]l; then
    echo "Yes, value is ${aa[FIRST[SECOND]]}"
else
    echo "No, the item has not been set yet."
fi

Upvotes: 0

Related Questions