Not fine, and the shell's pipe to the pit.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.