Passing arguments by reference

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

    #!/bin/bash
    
    append_string()
    {
    if [ -z "${!1}" ]; then
    eval "${1}='$2'"
    else
    eval "${1}='${!1}''${!3}''$2'"
    fi
    }
    
    PETS=''
    SEP='|'
    append_string "PETS" "cat" "SEP"
    echo "$PETS"
    append_string "PETS" "dog" "SEP"
    echo "$PETS"
    append_string "PETS" "hamster" "SEP"
    echo "$PETS"
    

    Output:

    cat
    cat|dog
    cat|dog|hamster
    

    Structure for calling that function is:

    append_string  name_of_var_to_update  string_to_add  name_of_var_containing_sep_char
    

    Name of variable is passed to fuction about PETS and SEP while string to append is passed the usual way as value. "${!1}" refers to contents of global PETS variable. In the beginning that variable is empty and contens is added each time we call the function. Separator character can be selected as needed. "eval" starting lines update PETS variable.

提交回复
热议问题