Passing arguments by reference

后端 未结 9 1960
挽巷
挽巷 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:55

    From the Bash man-page (Parameter Expansion):

        If the first  character of parameter is an exclamation  point (!), a
        level of variable indirection is  introduced. Bash uses the value of
        the variable  formed from the rest  of parameter as the  name of the
        variable; this variable  is then expanded and that value  is used in
        the rest  of the  substitution, rather than  the value  of parameter
        itself. This is known as indirect expansion.
    

    Therefore a reference is the variable's name. Here is a swap function using variable indirection that does not require a temporary variable:

    function swap()
    {   # 
        # @param VARNAME1 VARNAME2
        #
        eval "$1=${!2} $2=${!1}"
    }
    
    $ a=1 b=2
    $ swap a b
    $ echo $a $b
    2 1
    

提交回复
热议问题