Bash Shell 的 嵌套的While带来的问题

来源:互联网 发布:dns默认端口 编辑:程序博客网 时间:2024/06/12 23:12
今天遇到了一个问题,当使用了嵌套的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
换成重定向就可以了

原创粉丝点击