Map definition:
When using map, you need to declare it first, otherwise the result may be different from expected. Array can not be declared
Method 1:
declare -A myMap myMap["my03"]="03"
Method 2:
declare -A myMap=(["my01"]="01" ["my02"]="02") myMap["my03"]="03" myMap["my04"]="04"
Map initialization:
Similar to array, you can use brackets to initialize directly, or you can initialize data by adding them. Unlike array, when brackets are directly initialized, they are used as a key-value pair. When adding elements, the subscript may not be an integer.
myMap["my03"]="03" myMap["my04"]="04"
Output all keys, value, and lengths of Map:
#1) Output all keys#If the map is not declared using declare, then 0 will be output here, which does not match the expected output. There is one more output statement format than arr!echo ${!myMap[@]} #2) Output all values#The same format as array outputecho ${myMap[@]} #3) Output map length#The same format as array outputecho ${#myMap[@]}
Map traversal:
#1)Travel and find the corresponding value according to the keyfor key in ${!myMap[*]};do echo $key echo ${myMap[$key]} done #2) Iterate through all keysfor key in ${!myMap[@]};do echo $key echo ${myMap[$key]} done #3)Transfer all valuesfor val in ${myMap[@]};do echo $val done
Map test:
[root@cdh-143 shell-test]# more #!/bin/sh echo "one、definitionMap:declare -A myMap=([\"myMap00\"]=\"00\" [\"myMap01\"]=\"01\")" declare -A myMap=(["my00"]="00" ["my01"]="01") myMap["my02"]="02" myMap["my03"]="03" echo "2. Output all keys:" echo ${!myMap[@]} echo "Three, output all values:" echo ${myMap[@]} echo "IV. The length of the output map:" echo ${#myMap[@]} echo "Five. Traversal, find the corresponding value according to the key:" for key in ${!myMap[*]};do echo "key:"$key echo "value:"${myMap[$key]} done echo "Six. Go through all keys:" for key in ${!myMap[@]};do echo "key:"$key echo "value:"${myMap[$key]} done echo "7. Go through all values:" for val in ${myMap[@]};do echo "value:"$val done
Output:
[root@cdh-143 shell-test]# ./
1. Define Map:declare -A myMap=(["myMap00"]="00" ["myMap01"]="01")
2. Output all keys:
my02 my03 my00 my01
3. Output all values:
02 03 00 01
4. The length of the output map:
4
5. Traversal and find the corresponding value according to the key:
key:my02
value:02
key:my03
value:03
key:my00
value:00
key:my01
value:01
6. Go through all keys:
key:my02
value:02
key:my03
value:03
key:my00
value:00
key:my01
value:01
7. Go through all values:
value:02
value:03
value:00
value:01
[root@cdh-143 shell-test]#
This is the end of this article about the detailed explanation of the usage of Linux Shell Map. For more related Linux Shell Map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!