1. 程式人生 > >Bash Shell 的 巢狀的While帶來的問題

Bash Shell 的 巢狀的While帶來的問題

今天遇到了一個問題,當使用了巢狀的while之後,發現變數的值不會變更,例如下列程式碼
while 1; do
    a = 1
    cat file | while line || [ -n "${line}" ]; do
        a = 3
    done
    echo "${a}"
done

這段程式碼輸出的a一直都是2,而不是3。就是說內層的while中對a的修改並沒有作用到外層。

原因:

因為內層的while使用了管道,在Bash Shell中使用管道會生成一個子Shell,相當於呼叫了另一個Shell指令碼。

有這種需求的,可以改一下程式碼:

while 1; do
    a = 1
    while line || [ -n "${line}" ]; do
        a = 3
    done < file
    echo "${a}"
done
換成重定向就可以了