bash: piping output from a loop seems to change the scope within the loop - why?

后端 未结 2 1088
Happy的楠姐
Happy的楠姐 2020-12-06 21:32

I\'ve noticed that variable scope within a bash for loop seems to change if I pipe the output of the loop.

For example, here g remains changed after th

2条回答
  •  执笔经年
    2020-12-06 22:32

    As soon as you use a pipe (|) subshells are involved, mostly on both sides of the pipe.

    Therefore the for loop runs in a subshell and sets the variable inside that subshell. That's why after the loop the variable value stayed.

    In your first example there is no subshell, just multiple commands executed after each other.

提交回复
热议问题