return vs exit in function

return keyword

script:

func() {
    echo "a"
    return
    echo "b"
}

func

output:

a

return status code

script:

func() {
    return 99
}

func
echo $?

output:

99

return can’t return string

script:

func() {
    return "a"
}

func

output:

line 4: return: a: numeric argument required

use return to ‘return’ a string, method 1

Since function can’t really return any argument, but we still have this trick.

script:

func() {
    result="a"
}

func
echo $result

output:

a

Becareful:

func() {
    echo "Hello"
    echo "World"
}

result=$(func)
echo $result

output:

Hello World

exit in function, will kill the entire process

exit is a system level command

b.sh:

my_func() {
    echo "start my_func"
    exit 1
    echo "end my_func"          # will not be executed
}

a.sh:

source b.sh

echo "start a.sh"

my_func
echo "exit code of my_func:" $? # will not be executed
echo "end a.sh"                 # will not be executed

main.sh:

bash a.sh
echo "exit code of bash a.sh:" $?

output:

start a.sh
start my_func
exit code of bash a.sh: 1