0

following code gives error "foo:return: too many arguments"

f123() { echo $1; return 1; }
f124() { echo $1; return 1; }
foo() {
    return f123 "hello" && f124 "world"
}
foo

requirement is:

  • I want foo to execute f124 only if f123 returns non-zero return value
  • I want foo to return the return value of the last command that was successfully executed with non-zero return code

How do I do this in bash?

8
  • Ok. But still, how I do effective chaining Commented Jan 16, 2018 at 19:53
  • do a test with false ; foo $? ? Good luck. Commented Jan 16, 2018 at 19:53
  • Strike that trailing $? (now that I understand your code better). Good luck. Commented Jan 16, 2018 at 19:54
  • foo function does not take any arguments. I see that you are passing $? to foo. What is it doing? Can you please elaborate a bit? Commented Jan 16, 2018 at 19:55
  • Can you tell me how to avoid the error message "foo:return: too many arguments" ? Commented Jan 16, 2018 at 19:56

2 Answers 2

6

You don't need return here at all; the exit status of the function is the exit status of the last command executed. return is only need to return an explicit exit status.

foo() {
    f123 "hello" && f124 "world"
}

If f123 fails (has a non-zero exit status), f124 does not execute and the exit status of f123 is used as the exit status of foo. If f123 succeeds, then f124 does execute, and its exit status (zero or not) is used as the exit status of foo.

(If you really want f124 to execute when f123 fails, then use || instead of &&.)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. is the exit status of the function same as the return value of the function if one is provided?
Functions don't have return values in shell. They have exit statuses, and they can write to standard output, but they don't return values.
-1

Bash returns 0 on success but you are forcing to return 1 in your functions. Now, double ampersand operator && means: execute if previous command was successful, i.e. it returned 0. You will have to do it manually if you insist on return values greater than 0

f123() { echo $1; return 1; }
f124() { echo $1; return 1; }
foo() {
    f123 "hello"
    r1=$?
    if [ "$r1" -gt 0 ] ; then
        f124 "world"
        r2=$?
        if [ "$r2" -gt 0 ]; then
            r1=$r2
        fi
    fi
    return $r1
}

2 Comments

What's the return value from foo()?
@chepner I disagree, it replies the answer as requested. || follows the bash logic where 0 is success. Also the code is verbose but correct.

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.