bash - how to return values from a bash function
What I wanted to do was to set a variable in bash from a function. Not as easy as I would have hoped.
Returning values from bash functions
Here is the choice I used from the article:
The other way to return a value is to write your function so that it accepts a variable name as part of its command line and then set that variable to the result of the function:
function myfunc()
{
local __resultvar=$1
local myresult='some value'
eval $__resultvar="'$myresult'"
}
myfunc result
echo $result
It seems to work just fine. Here is the code that I used in my common.sh function, for the work script RWS-1891.sh:
get_choice () {
# https://www.linuxjournal.com/content/return-values-bash-functions
# sets the passed in variable to set later
local __resultvar=$1
choice_arg=$2
if [ -z "$choice_arg" ]
then
choice_arg="HERE"
else
check_if_ask_for_help $choice_arg
check_if_invalid_choicd $choice_arg
fi
# sets the value into the passed in variable
eval $__resultvar="'$choice_arg'"
}
called like this:
#### https://linuxhint.com/bash_lowercase_uppercase_strings/
#### upper-case the passed in choice
#### - have to use for bash 3.2.57
#### - can't use nice bash 4+ way - silly macOS
#
MY_CHOICE=`echo $1 | tr "[:lower:]" "[:upper:]"`
echo "choice: $MY_CHOICE"
get_choice MY_CHOICE "$MY_CHOICE"
Works pretty well.