Linux Shell: Map Usage

Map definitions:

When using the map, you need to declare, otherwise the results may differ from expectations, array can not be declared

Mode 1:

declare -A myMap
myMap["my03"]="03"

Option 2:

declare -A myMap=(["my01"]="01" ["my02"]="02")
myMap["my03"]="03"
myMap["my04"]="04"

Map Initialization:

Similarly the array can be initialized directly parentheses, may be initialized by means of the data added to the array is different, the use of parenthesis directly initialized to a key-value pair, when the added elements, the subscript can not be an integer

myMap["my03"]="03"
myMap["my04"]="04"

Map all output key, value, length:

# 1 ) output all Key 
# Failure to use declare statements map, then where will output 0, inconsistent with the expected output, where the output format statement than an arry! 
echo $ {! the myMap [@]} 
# 2 ) outputs all value 
# Same array output format 
echo $ {the myMap [@]} 
# . 3 ) output of the map length 
# Same array output format 
echo $ {# the myMap [@]}

Map traversal:

# 1 ) traversed to find the corresponding value according to Key
 for Key in $ {the myMap [*]!}; Do 
  echo $ Key
   echo $ {the myMap [$ Key]}
 DONE 
# 2 ) through all the Key
 for Key in $ {! the myMap [@]}; do 
  echo $ Key
   echo $ {the myMap [Key $]}
 DONE 
# . 3 ) through all of the value
 for Val in $ {the myMap [@]}; do 
  echo $ Val
 DONE

Map Test:

[root@cdh-143 shell-test]# more map-test.sh
#!/bin/sh

echo "一、定义Map:declare -A myMap=([\"myMap00\"]=\"00\" [\"myMap01\"]=\"01\")"
declare -A myMap=(["my00"]="00" ["my01"]="01")
myMap["my02"]="02"
myMap["my03"]="03"

echo "Second, the output of all the Key: " 
echo $ {! The myMap [@]} 

echo  " three, the output of all value: " 
echo $ {the myMap [@]} 

echo  " four, the length of the output of the map: " 
echo $ {# the myMap [ @]} 

echo  " five, traversing, according to the key to find the corresponding value: " 
for key in $ {the myMap [*]};! do 
  echo  " key: " $ key
   echo  " value: " $ {the myMap [$ key]}
 DONE 

echo  " six, through all the Key: " 
for Key in $; {myMap [@]!}Do 
  Echo "key:"$key
  echo "value:"${myMap[$key]}
done

echo "七、遍历所有value:"
for val in ${myMap[@]};do
  echo "value:"$val
done

Output:

[the root @ CDH- 143 the shell-Test] # ./map-test. SH 
I. Definitions the Map: DECLARE -A the myMap = ([ " myMap00 " ] = " 00 " [ " myMap01 " ] = " 01 " ) 
II. output All Key: 
my02 my03 MY00 MY01 
Third, the output of all value: 
02  03  00  01 
Fourth, the length of the output map of: 
4 
V. traversal, find the corresponding value in accordance Key: 
Key: my02 
value: 02 
Key: my03 
value: 03 
Key: MY00 
value: 00 
Key: MY01 
value: 01  
Sixth, through all the key:
Key: my02
value:02
key:my03
value:03
key:my00
value:00
key:my01
value:01
七、遍历所有value:
value:02
value:03
value:00
value:01
[root@cdh-143 shell-test]#

 

Guess you like

Origin www.cnblogs.com/yy3b2007com/p/11267237.html