How to modify a global variable within a function in bash?

后端 未结 8 2144
情深已故
情深已故 2020-12-02 09:20

I\'m working with this:

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

I have a script like below:

#!/bin/bas         


        
8条回答
  •  猫巷女王i
    2020-12-02 09:29

    When you use a command substitution (ie the $(...) construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way - a subshell cannot modify the environment of its parent shell. Your variable e is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:

    myfunc() {
        echo "Hello"
    }
    
    var="$(myfunc)"
    
    echo "$var"
    

    Gives:

    Hello
    

    For a numerical value from 0-255, you can use return to pass the number as the exit status:

    mysecondfunc() {
        echo "Hello"
        return 4
    }
    
    var="$(mysecondfunc)"
    num_var=$?
    
    echo "$var - num is $num_var"
    

    Gives:

    Hello - num is 4
    

提交回复
热议问题