idioms for returning multiple values in shell scripting

后端 未结 10 872
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 20:56

Are there any idioms for returning multiple values from a bash function within a script?

http://tldp.org/LDP/abs/html/assortedtips.html describes how to echo multipl

相关标签:
10条回答
  • 2020-12-29 21:35

    This question was posted 5 years ago, but I have some interesting answer to post. I have just started learning bash, and I also encounter to the same problem as you did. I think this trick might be helpful:

    #!/bin/sh
    
    foo=""
    bar=""
    
    my_func(){
        echo 'foo="a"; bar="b"'
    }
    
    eval $(my_func)
    echo $foo $bar
    # result: a b
    

    This trick is also useful for solving a problem when a child process can not send back a value to its parent process.

    0 讨论(0)
  • 2020-12-29 21:42

    Yet another way:

    function get_tuple()
    {
      echo -e "Value1\nValue2"
    }
    
    IFS=$'\n' read -d '' -ra VALUES < <(get_tuple)
    echo "${VALUES[0]}" # Value1
    echo "${VALUES[1]}" # Value2
    
    0 讨论(0)
  • 2020-12-29 21:49

    you can make use of associative arrays with you have bash 4 eg

    declare -A ARR
    function foo(){
      ...
      ARR["foo_return_value_1"]="VAR1"
      ARR["foo_return_value_2"]="VAR2"
    }
    

    you can combine them as strings.

    function foo(){
      ...
      echo "$var1|$var2|$var3"
    }
    

    then whenever you need to use those return values,

    ret="$(foo)"
    IFS="|"
    set -- $ret
    echo "var1 one is: $1"
    echo "var2 one is: $2"
    echo "var3 one is: $3"
    
    0 讨论(0)
  • 2020-12-29 21:52

    I am new to bash, But found this code helping.

    function return_multiple_values() {
            eval "$1='What is your name'"
            eval "$2='my name is: BASH'"
        }
        
        return_var=''
        res2=''
        return_multiple_values return_var res2
        echo $return_var
        echo $res2
    
    0 讨论(0)
提交回复
热议问题