Set a parent shell's variable from a subshell

后端 未结 7 1432
野性不改
野性不改 2020-11-27 03:58

How do I set a variable in the parent shell, from a subshell?

a=3
(a=4)
echo $a
相关标签:
7条回答
  • 2020-11-27 04:37

    The whole point of a subshell is that it doesn't affect the calling session. In bash a subshell is a child process, other shells differ but even then a variable setting in a subshell does not affect the caller. By definition.

    Do you need a subshell? If you just need a group then use braces:

    a=3
    { a=4;}
    echo $a
    

    gives 4 (be careful of the spaces in that one). Alternatively, write the variable value to stdout and capture it in the caller:

    a=3
    a=$(a=4;echo $a)
    echo $a
    

    avoid using back-ticks ``, they are deprecated and can be difficult to read.

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