Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

bash: return vs exit

3 views
Skip to first unread message

alex

unread,
Apr 1, 2022, 7:21:08 AM4/1/22
to
#!/bin/bash

# return used
f1() {
for i in 1; do
(
return 123
)
echo ++ $?
done
}

# exit used
f2() {
for i in 1; do
(
exit 123
)
echo ++ $?
done
}

echo + f1
f1
echo + f2
f2

Output:

+ f1
++ 123
+ f2
++ 123

Functional difference between f1() and f2()?

J.O. Aho

unread,
Apr 1, 2022, 9:54:10 AM4/1/22
to

On 01/04/2022 13.21, alex wrote:

> Output:
>
> + f1
> ++ 123
> + f2
> ++ 123
>
> Functional difference between f1() and f2()?

In this case, there ain't much difference, but here is a script where
they will cause you more difference:
--- test_script ---
#!/bin/bash
## return used
f1() {
return 123
}

## exit used
f2() {
exit 123
)
}

## run functions
echo + f1
f1
echo "return value: $?"
echo + f2
f2
echo "exit value: $?"
--- eof ---

--- output ---
+ f1
return value: 123
+ f2
--- eof --

So exit will cause a full stop on the level outside, while return will not.

Most likely you want to use return in functions, even if exit seems to
work in some cases, but you may get an unexpected flow in your script.

--

//Aho

alex

unread,
Apr 1, 2022, 10:51:45 AM4/1/22
to
Il 01/04/22 15:54, J.O. Aho ha scritto:
Thanks :D
0 new messages