Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idioms for returning multiple values in shell scripting

Tags:

idioms

shell

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.

like image 827
Wang Avatar asked Mar 21 '10 21:03

Wang


People also ask

What is the meaning of 2 >& 1?

The 1 denotes standard output (stdout). The 2 denotes standard error (stderr). So 2>&1 says to send standard error to where ever standard output is being redirected as well.

Can bash function return multiple values?

Yes, bash 's return can only return numbers, and only integers between 0 and 255.

Can return have multiple values?

Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Which language can return multiple values from a function?

But there are two built-in and easy ways to return multiple values from a function in JavaScript with Array and Object.


1 Answers

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.

like image 140
fronthem Avatar answered Oct 17 '22 08:10

fronthem