Via:
set -o nounset
1) The presence of an indexed array, such as:
myArray=( "red" "black" "blue" )
What is the shortest way to check if item 1 is installed?
I sometimes use the following:
test "${#myArray[@]}" -gt "1" && echo "1 exists" || echo "1 doesn't exist"
I would like to know if there is a preferred one.
2) How to deal with inconsistent indices?
myArray=() myArray[12]="red" myArray[51]="black" myArray[129]="blue"
How to quickly check that "51" is already installed, for example?
3) How to deal with associative arrays?
declare -A myArray myArray["key1"]="red" myArray["key2"]="black" myArray["key3"]="blue"
How to quickly check that "key2" is already in use, for example?
thank
EDITING
It seems to me the easiest way:
if test "${myArray['key_or_index']+isset}" then echo "yes" else echo "no" fi;
This works for both indexed and associative arrays. Errors are not displayed with the -o noun set.
Thanks to DoubleDown for the title.
arrays bash indexing key
Luca Borrione Nov 04 2018-12-12T00: 00Z
source share