Grouping commands in curly braces and piping does not preserve variable

后端 未结 2 587
情书的邮戳
情书的邮戳 2021-01-02 22:50

Say I have a file myfile in my current working directory. I want to set a variable if a command executes normally, but also use its result.

$ ls         


        
相关标签:
2条回答
  • 2021-01-02 23:37

    You can use BASH_SUBSHELL variable to verify whether you're in subshell or not.

    # BASH_SUBSHELL will print level of subshell from top due to pipe
    { unset v && ls file && v=3 && echo "$BASH_SUBSHELL - $v"; } | nl
         1  file
         2  1 - 3
    
    # outside BASH_SUBSHELL will print 0
    echo "$BASH_SUBSHELL - $v";
    0 -
    

    You can use for piped command it prints 1 meaning it is in a subshell hence value of v isn't available outside (evident from 2nd output)

    0 讨论(0)
  • 2021-01-02 23:53

    It's not the curly braces that are causing a subshell to be created, it's the pipe.

    To prove it:

    $ { ls && v=3; } > tmp
    $ echo "$v"
    3
    

    To quote Greg:

    In most shells, each command of a pipeline is executed in a separate SubShell.

    0 讨论(0)
提交回复
热议问题