Using:
set -o nounset
1) Having an indexed array like:
myArray=( "red" "black" "blue" )
Which is the shortest way to check if element 1 is set?
I sometimes use the following:
test "${#myArray[@]}" -gt "1" && echo "1 exists" || echo "1 doesn't exist"
I would like to know if there's a preferred one.
2) How to deal with non-consecutive indexes?
myArray=()
myArray[12]="red"
myArray[51]="black"
myArray[129]="blue"
How to quick check that '51' is already set for example?
3) How to deal with associative arrays?
declare -A myArray
myArray["key1"]="red"
myArray["key2"]="black"
myArray["key3"]="blue"
How to quick check that 'key2' is already used for example?
Thanks
EDITED
The simplest way seems to me:
if test "${myArray['key_or_index']+isset}"
then
echo "yes"
else
echo "no"
fi;
This works for both indexed and associative arrays. No errors shown with set -o nounset.
Thanks to doubleDown for the headup.
I wrote a function to check if a key exists in an array in Bash:
Example
Tested with GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)
To check if the element is set (applies to both indexed and associative array)
Basically what
${array[key]+abc}
does isarray[key]
is set, returnabc
array[key]
is not set, return nothingReferences:
See Parameter Expansion in Bash manual and the little note
This answer is actually adapted from the answers for this SO question: How to tell if a string is not defined in a bash shell script?
A wrapper function:
For example
tested in bash 4.3.39(1)-release
This is the easiest way I found for scripts.
<search>
is the string you want to find,ASSOC_ARRAY
the name of the variable holding your associative array.Dependign on what you want to achieve:
key exists:
key exists not:
value exists:
value exists not:
Unfortunately, bash give no way to make difference betwen empty and undefined variable.
But there is some ways:
(give no answer)
And for associative array, you could use the same:
You could do the job without the need of externals tools (no printf|grep as pure bash), and why not, build checkIfExist() as a new bash function:
or even create a new getIfExist bash function that return the desired value and exit with false result-code if desired value not exist:
From man bash, conditional expressions:
example:
This will show that both foo[bar] and foo[baz] are set (even though the latter is set to an empty value) and foo[quux] is not.