0

I'm trying to catch a return value from a function in bash, that modify a global variable. Works perfectly with funtions with no parameters:

#!/bin/bash

tes=2
testfunction(){
        tes=3
        tes_str="string result"
        return 0
}
if output=testfunction; then
        echo "OK"
else
        echo "KO"
fi
echo $tes
echo $tes_str

But no with parameters:

#!/bin/bash

tes=2
testfunction(){
        tes=3
        tes_str="string result"
        return 0
}
if output=$(testfunction "AA" "BB"); then
        echo "OK"
else
        echo "KO"
fi
echo $tes
echo $tes_str

Because for bash, parameters ("AA" or "BB") are a command, and I must put it in backets (but if use backets, can't modify global variables). How can I do it? I'm stucked. Regards

3
  • 2
    Works perfectly with funtions with no parameters No it doesn't, your code is invalid. output=testfunction only assigns the text testfunction to output. Commented Nov 3, 2020 at 11:26
  • @Souf : Your first example does not execute testfunction. Your second example does. You can easily verify this by doing a echo heloo >&2 inside testfunction. Commented Nov 3, 2020 at 12:07
  • Yes, It was a mistake, it's my fault, I wrote the simple code for this post, trying to explain the issue, catching the return value and calling a function with parameters. Commented Nov 3, 2020 at 17:18

1 Answer 1

1

Why use output? Just remove it and run the function.

if testfunction; then

Notes:

  • output=testfunction is assigning the text testfunction to the variable output.
  • output=$(testfunction) will not work, because $(...) runs everything inside a subshell.
Sign up to request clarification or add additional context in comments.

3 Comments

Because without output assignment, I can't catch the return value. And first option yes, it was a mistake, it's my fault. With if testfunction; then I can't catch the return value, and I can't pass the parameters.
I do not follow - no, I disagree with your statements. You can "catch" the return value and yes you can pass arguments. With command substitution you save output of a command, you still may do that with temporary file. repl bash example
Yes, it works... I don't know why yesterday I can't do it... The only response is that I'm stupid... :(

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.