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

后端 未结 8 2143
情深已故
情深已故 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条回答
  •  悲&欢浪女
    2020-12-02 09:34

    I had a similar problem, when I wanted to automatically remove temp files I had created. The solution I came up with was not to use command substitution, but rather to pass the name of the variable, that should take the final result, into the function. E.g.

    #! /bin/bash
    
    remove_later=""
    new_tmp_file() {
        file=$(mktemp)
        remove_later="$remove_later $file"
        eval $1=$file
    }
    remove_tmp_files() {
        rm $remove_later
    }
    trap remove_tmp_files EXIT
    
    new_tmp_file tmpfile1
    new_tmp_file tmpfile2
    

    So, in your case that would be:

    #!/bin/bash
    
    e=2
    
    function test1() {
      e=4
      eval $1="hello"
    }
    
    test1 ret
    
    echo "$ret"
    echo "$e"
    

    Works and has no restrictions on the "return value".

提交回复
热议问题