Passing arguments by reference

后端 未结 9 1951
挽巷
挽巷 2020-12-01 01:13

I want to ask if it is possible to pass arguments to a script function by reference:

i.e. to do something that would look like this in C++:



        
9条回答
  •  抹茶落季
    2020-12-01 01:47

    Ok, so this question has been waiting for a 'real' solution for some time now, and I am glad to say that we can now accomplish this without using eval at all.

    The key to remember is to declare a reference in both the caller as the callee, at least in my example:

    #!/bin/bash
    
    # NOTE this does require a bash version >= 4.3
    
    set -o errexit -o nounset -o posix -o pipefail
    
    passedByRef() {
    
        local -n theRef
    
        if [ 0 -lt $# ]; then
    
            theRef=$1
    
            echo -e "${FUNCNAME}:\n\tthe value of my reference is:\n\t\t${theRef}"
    
            # now that we have a reference, we can assign things to it
    
            theRef="some other value"
    
            echo -e "${FUNCNAME}:\n\tvalue of my reference set to:\n\t\t${theRef}"
    
        else
    
            echo "Error: missing argument"
    
            exit 1
        fi
    }
    
    referenceTester() {
    
        local theVariable="I am a variable"
    
        # note the absence of quoting and escaping etc.
    
        local -n theReference=theVariable
    
        echo -e "${FUNCNAME}:\n\tthe value of my reference is:\n\t\t${theReference}"
    
        passedByRef theReference
    
        echo -e "${FUNCNAME}:\n\tthe value of my reference is now:\n\t\t${theReference},\n\tand the pointed to variable:\n\t\t${theVariable}"
    
    }
    
    # run it
    
    referenceTester
    

提交回复
热议问题