First my sourcecode to test the returning method of bash functions:
function oidev.fnc.bash.example.fncreturnstringvalue
{
echo "ABC"
return 1
}
and the caller function:
function oidev.fnc.bash.example.fncreturnstringvaluecaller
{
local FNCVALUE
local FNCSTRING
FNCSTRING=$(oidev.fnc.bash.example.fncreturnstringvalue && FNCVALUE="$?" || FNCVALUE="$?")
# String OK but Value empty
echo "VALUE : $FNCVALUE"
echo "STRING: $FNCSTRING"
unset FNCVALUE
unset FNCSTRING
oidev.fnc.bash.example.fncreturnstringvalue && FNCVALUE="$?" || FNCVALUE="$?"
# Value OK and String on STDOUT
echo "VALUE : $FNCVALUE"
echo "STRING: $FNCSTRING"
}
The output in bash:
VALUE :
STRING: ABC
ABC
VALUE : 1
STRING: (surely empty, but echoed from the function)
`
And now my simple question:
Is it possible to get the returning string and returning value into two different variables by a single line construction?
I don't want to use globals, nore the use of if $? after the sub-call!
Many thanks for help, and sorry for my german-english!
Try this, maybe helps:
func() {
echo 'abc'
return 111
}
read var1 var2 <<<$(func; echo $?)
echo "var1 $var1"
echo "var2 $var2"
will print:
var1 abc
var2 111
workaround for the "spaces problem" - now, haven't better idea as use an helper function like this
func() {
echo 'abc def'
return 111
}
runner() {
ret=$(func)
echo $? $ret
}
read -r var2 var1 <<<$(runner func)
echo "var1 $var1"
echo "var2 $var2"
or using a helper variable and switching the variable order
func() {
echo 'abc def'
return 111
}
read -r var2 var1 <<<$(res=$(func); echo $? $res)
echo "var1 $var1"
echo "var2 $var2"
both will return
var1 abc def
var2 111
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With