I've used the bash shell, and it's not a short time. But I've never learned to shell, at least not so seriously as C + +. Usually write some basic script no problem, do not understand can also Google, Baidu. On the last day of 2014, it fell into the pit.
In fact, the script is very simple, the code is basically as follows:
#!/bin/Bashdeclare-A FILES #关联数组 bash version >=4.0CatEx_files | whileRead Line DoKey=`Echo$line |awk '{print $}'' Value=`Echo$line |awk '{print $}'' files[$key]=$value DoneEcho${files[@]}
In fact, each time you read a line from a file, and then break out the key, value, and then assign a value to the map from one row by column. Yes, the output map is actually empty. So, began a few hours of tossing.
The first thought was the reason for the associative array, because it was used as an associative array. But Google, Baidu, man Bash, are so used. In files[$key]= $value It is correct to print here, but the files are empty outside the while. Then the suspicion is that the key is the reason for the string, and then another script test, the key is a string completely no problem. Think of this situation should be files into a local variable (in C + + way, so think), but I declare files when the local AH. Is that why while read? So I searched for the "while read local variable" and searched for a lot of sub-shell related problems, which is my problem.
In Cat Ex_files | While ... done in this code, the cat ex_files is running in the current shell, while ... doing is running in a child shell, so the current shell array is not assigned a value. The solution to the change is good:
#!/bin/Bashdeclare-A FILES whileRead Line DoKey=`Echo$line |awk '{print $}'' Value=`Echo$line |awk '{print $}'' files[$key]=$value Done<Ex_filesEcho${files[@]}
Note that ex_files may not be able to read the last line because of the line break
Not fine, and the shell's pipe to the pit.