Recently, when I wrote a shell script, I defined some variables in the while loop, but when I called them after exiting, we found that the variable values were empty, and it took a whole day to find the cause:
I'm just doing a rough experiment here, explaining where the problem is, at the beginning of the code:
#!/bin/shcat Config.ini | While read vardoa= $varecho $adoneecho "$a mark"
[Email protected]_102 ~]# cat config.initest[[email protected]_102 ~]#./a.sh Test Mark
This time we found that the variable that was defined in the while loop, why the value of the variable is empty after the while loop exits, is not the problem of the local variable, which is used in the export test:
[Email protected]_102 ~]# cat a.sh #!/bin/shcat Config.ini | While read Vardoexport a= $varecho $adoneecho "$a mark" [[Email protected]_102 ~]#./a.shtest Mark
Still not, so began a long trip to Google, and later found that this is because of the pipeline character redirection caused by the code to try to change the first:
[Email protected]_102 ~]# cat a.sh #!/bin/shwhile read Vardoexport a= $varecho $adone < Config.iniecho "$a mark" [email protected]_102 ~]#./a.sh testtest Mark
Success!!!!!!!!
Why this problem here, in fact, the reason is very simple, when bash in the use of pipe characters, will produce Subshell, so that in this subshell to the variable assignment only in its own subshell to take effect, will not affect the shell script itself process.
But Ksh now has a feature that allows the assignment of variables in the pipeline to be reflected in the parent shell, which is why people on the internet are asking that such code is OK in the K shell.
So here, if we use Ksh, we can print out the variable value of the variable:
[Email protected]_102 ~]# cat a.sh #!/bin/kshcat Config.ini | While read Vardoexport a= $varecho $adoneecho "$a mark" [[Email protected]_102 ~]#./a.sh testtest Mark
This article is from the "Red Mansions Dream" blog, please be sure to keep this source http://leidongya.blog.51cto.com/7375845/1588066
An issue in which variables defined in a while loop under a pipe are referenced as empty when exiting a while loop