shell while內擷取外部變數內容

來源:互聯網
上載者:User

標籤: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內擷取外部變數內容

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.