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.
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.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With