How do I return multiple values from a function in Shell?

How do I return multiple values from a function in Shell?

Use declare -n var_name to give var_name the nameref attribute. nameref gives your function the ability to “pass by reference” which is commonly used in C++ functions to return multiple values.

How can a function return multiple values?

You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas.

How do you return a value from a Bash function?

To actually return arbitrary values to the caller you must use other mechanisms. The simplest way to return a value from a bash function is to just set a global variable to the result. Since all variables in bash are global by default this is easy: The code above sets the global variable myresult to the function result.

Why is my bash script not returning a value?

What you wrote didn’t work because the command substitution $ (…) expands to the output of the function, which in your code is either the error message or empty, never 1. Assign to one or more variable inside the function and read those variables later. I’ve had conflicting results in this area myself.

How to return multiple values from a function?

Shell Programming and Scripting I’ve been trying to write a command-line function to grab a website’s MX records and their ip addresses. The code below works with domains that only have one MX record: function kmx { mx=`host -t MX $1 | awk ‘ { print $7 }’`; ip=`host $mx | sed ‘/IPv6/d;/handled/d’ | awk ‘ { print $4 }’`;

How to pass a function as a parameter in Bash?

A better approach is to use local variables in your functions. The problem then becomes how do you get the result to the caller. One mechanism is to use command substitution: Here the result is output to the stdout and the caller uses command substitution to capture the value in a variable. The variable can then be used as needed.