Why is the return code from my function not what I expect?

0
2
Asked By CuriousCoder92 On

I'm working on a Bash script where I have a couple of functions. When I press CTRL-C (which sends a SIGINT), I'm getting an unexpected return code from my function. Here's the code I'm using:

```bash
#!/bin/bash

bar() {
echo bar
return
}

foo() {
echo foo
bar
echo "Return code from bar(): $?"
exit
}
trap foo SIGINT

while :; do
sleep 1;
done
```

When I run the script and then interrupt it, I expect the output to show the return code from `bar()` as 0, but instead, it shows 130. Why isn't the return statement in the `bar` function giving me the success code of the `echo` command?

3 Answers

Answered By BashBuddha On

Exactly! The function is returning a status of 0 from 'bar' only if the last command executed successfully. In your case, the last command is the `return` statement without an explicit code, which is treated like `return 0`. So just strip the return line to let the function return the exit code of `echo` instead.

Answered By CodeWhiz On

You got it! The `return` is actually the last command in your function, and since it's without arguments, it returns 0 by default. If you remove that `return` statement, your function's last executed command (which is `echo`) will dictate the exit code. Just make sure the last command in `bar()` is the `echo` line to get the expected result!

Answered By ScriptSavvy77 On

When you use `return` without specifying an exit status, it doesn't mean it automatically returns the exit code of the last command executed. According to the POSIX spec, if `return` is in a `trap` handler, its exit status is based on the last command run *before* the handler is called. In your case, the `bar` function's `return` is treated this way since it's running within a trap. So, when you send a SIGINT, the return code reflects the signal instead—hence 130, which is the result of the interrupt (128 + 2). You could check out a thread on this from the bash mailing list for deeper insights.

GratefulUser84 -

Thanks for clarifying that for me!

TechNerd101 -

So, would it be correct to say that Bash will always return the last statement's exit code in a function? Maybe in this case, just removing that `return` would solve my issue?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.