3

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for this perfect answer, the <<< construction..., google knows!
This will not work if the string returned by func() contains spaces.
Yes, but it can be quoted inside the function with echo "\'a b c\'" to one variable to READ from the Caller
two statements. var1=$(func); var2=$?
@KlausBaumann read splits based on IFS. quotes don't matter unless you put quotes in IFS
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.