idioms for returning multiple values in shell scripting

Wang picture Wang · Mar 21, 2010 · Viewed 37.1k times · Source

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 multiple values and process the results (e.g., example 35-17), but that gets tricky if some of the returned values are strings with spaces in.

A more structured way to return would be to assign to global variables, like

foo () {
    FOO_RV1="bob"
    FOO_RV2="bill"
}

foo
echo "foo returned ${FOO_RV1} and ${FOO_RV2}"

I realize that if I need re-entrancy in a shell script I'm probably doing it wrong, but I still feel very uncomfortable throwing global variables around just to hold return values.

Is there a better way? I would prefer portability, but it's probably not a real limitation if I have to specify #!/bin/bash.

Answer

mivk picture mivk · Aug 21, 2016

In the special case where your values never contain spaces, this read trick can be a simple solution:

get_vars () {
  #...
  echo "value1" "value2"
}

read var1 var2 < <(get_vars)
echo "var1='$var1', var2='$var2'"

But of course, it breaks as soon as there is a space in one of the values. You could modify IFS and use a special separator in your function's echo, but then the result is not really simpler than the other suggested solutions.