Set a parent shell's variable from a subshell

后端 未结 7 1480
野性不改
野性不改 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:16

    You can output the value in the subshell and assign the subshell output to a variable in the caller script:

    # subshell.sh
    echo Value
    
    # caller
    myvar=$(subshell.sh)
    

    If the subshell has more to output you can separate the variable value and other messages by redirecting them into different output streams:

    # subshell.sh
    echo "Writing value" 1>&2
    echo Value
    
    # caller
    myvar=$(subshell.sh 2>/dev/null) # or to somewhere else
    echo $myvar
    

    Alternatively, you can output variable assignments in the subshell, evaluate them in the caller script and avoid using files to exchange information:

    # subshell.sh
    echo "a=4"
    
    # caller
    # export $(subshell.sh) would be more secure, since export accepts name=value only.
    eval $(subshell.sh)
    echo $a
    

    The last way I can think of is to use exit codes but this covers the integer values exchange only (and in a limited range) and breaks the convention for interpreting exit codes (0 for success non-0 for everything else).

提交回复
热议问题