2013-08-28 123 views
1

我有一個更大的腳本,但這種較小的顯示問題:爲什麼這個變量沒有被改變?

#!/bin/bash 
x=0 
if [[ $x == 0 ]] 
then 
    ls | while read L 
    do 
    x=5 
    echo "this is a file $L and this is now set to five --> $x" 
    done 
fi 
echo "this should NOT be 0 --> $x" 

如果變量被設置在while循環之外,那麼它可以作爲我的期望。 bash版本是3.2.25(1) - 釋放(x86_64-redhat-linux-gnu)。如果這是顯而易見的事情,我會覺得很蠢。

+0

這是一個常見的問題。閱讀常見問題:http://mywiki.wooledge.org/BashFAQ/024 –

+0

另一個偉大的鏈接:[爲什麼你不應該解析ls的輸出](http://mywiki.wooledge.org/ParsingLs) –

+0

選擇類似線程:http://stackoverflow.com/questions/13233452/bash-variable-change-doesnt-persist。 – konsolebox

回答

3

設置爲5的x位於子外殼中(因爲它是管道的一部分),並且子外殼中發生的操作不會影響父外殼。

您可以避免子shell並得到結果,你通過使用進程替換在bash預期:現在

#!/bin/bash 
x=0 
if [[ $x == 0 ]] 
then 
    while read L 
    do 
    x=5 
    echo "this is a file $L and this is now set to five --> $x" 
    done < <(ls) 
fi 
echo "this should NOT be 0 --> $x" 

while循環的主要shell進程的一部分(只有ls是在子-process),所以變量x受到影響。

我們可以討論另一次解析ls輸出的優點;這在很大程度上與問題中的問題有關。

另一種選擇是:

#!/bin/bash 
x=0 
if [[ $x == 0 ]] 
then 
    ls | 
    { 
    while read L 
    do 
    x=5 
    echo "this is a file $L and this is now set to five --> $x" 
    done 
    echo "this should NOT be 0 --> $x" 
    } 
fi 
echo "this should be 0 still, though --> $x" 
+0

哎唷!多麼尷尬。感謝Aleks-Daniel Jakimenko和Jonathan Leffler。 – Allen

相關問題