標籤:style blog http io ar color os 使用 sp
一、問題
問題很簡單,看下面一段tmp.sh代碼:
#!/bin/shx="this is the initial value of x"cat /tmp/tmp | while read line;do x="$line" echo $xdoneecho x = $x
/tmp/tmp的內容
1,a
執行 ./tmp.sh,正常x變數是藍色的“1,a”,但是實際的結果卻是紅色部分:
[[email protected] ~]$ ./tmp.sh 1,ax = this is the initial value of x
問題很明顯,變數x在while內修改之後,並沒有帶到外面來,為什麼哪?
二、答案
經過幾經尋找,終於發現問題的原因:是因為啟動了子進程,而變數x在子進程修改之後,並沒有帶入到父進程。原文如下:
This is because in the Bourne shell redirected control structures run in a subshell, so the value of x only gets changed in the subshell, and is lost when the loop ends.In other shells the same result may be seen because of the way pipelines are handled. In shells other than ksh (not pdksh) and zsh elements of a pipeline are run in subshells. In ksh and zsh, the last element of the pipeline is run in the current shell.An alternative for non-Bourne shells is to use redirectioninstead of the pipeline
如何解決哪?
1、一般方法:
#!/bin/shx="this is the initial value of x"while read line;do x="$line" echo $xdone < /tmp/tmpecho x = $x
運行:
[qiu.li@l-tdata1.tkt.cn6 ~]$ ./tmp.sh 1,ax = 1,a
2、優雅一些的解決方案:
#!/bin/shx="this is the initial value of x"exec 3<&0 # save stdinexec < /tmp/tmpwhile read line; do x=$line echo $xdoneexec 0<&3 # restore stdinecho x = $x
本人英文實在有限,原因只能貼出英文:
Note that putting #!/bin/sh at the top of a script doesn‘t guarantee you‘re using the Bourne shell. Some systems link /bin/sh to some other shell. Check your system documentation to find out what shell you‘re really getting in this case.
大概是說: 注意最上面的#!/bin/sh 如果使用其他的此指令碼不能運行。但是在有些系統/bin/sh 被指定到了其他的shell解譯器裡面,也是出現不一樣的結果。詳細的參考:http://www.cnblogs.com/liqiu/p/4107948.html
shell while內擷取外部變數內容