scope of variable in pipe

后端 未结 6 1484
余生分开走
余生分开走 2020-12-18 10:51

The following shell scrip will check the disk space and change the variable diskfull to 1 if the usage is more than 10% The last echo always shows

6条回答
  •  一生所求
    2020-12-18 11:13

    This is a side-effect of using while in a pipeline. There are two workarounds:

    1) put the while loop and all the variables it uses in a separate scope as demonstrated by levislevis86

    some | complicated | pipeline | {
        while read line; do
            foo=$( some calculation )
        done
        do_something_with $foo
    }
    # $foo not available here
    

    2) if your shell allows it, use process substitution and you can redirect the output of your pipeline to the input of the while loop

    while read line; do
        foo=$( some calculation )}
    done < <(some | complicated | pipeline)
    do_something_with $foo
    

提交回复
热议问题