代码之家  ›  专栏  ›  技术社区  ›  swampsjohn

在bash中读取多行而不生成新的子shell?

  •  13
  • swampsjohn  · 技术社区  · 14 年前

    我想做点什么

    var=0  
    grep "foo" bar | while read line; do  
       var=1  
    done
    

    不幸的是,这不起作用,因为管道会导致while在子shell中运行。有更好的方法吗?如果有其他解决方案,我不需要使用“读”。

    我看过 Bash variable scope 这是相似的,但我不能从中得到任何有用的东西。

    2 回复  |  直到 8 年前
        1
  •  20
  •   that other guy    8 年前

    如果你真的在做一些简单的事情,你甚至不需要 while read 循环。以下内容将起作用:

    VAR=0
    grep "foo" bar && VAR=1
    # ...
    

    如果您确实需要循环,因为循环中正在发生其他事情,您可以从 <( commands ) 过程替换:

    VAR=0
    while read line ; do
        VAR=1
        # do other stuff
    done <  <(grep "foo" bar)
    
        2
  •  2
  •   ghostdog74    14 年前

    那就不要用烟斗,把灰丢了。

    var=1
    while read line
    do  
       case "$line" in
        *foo* ) var=1
       esac   
    done <"file"
    echo "var after: $var"