Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between echo and return in bash? [duplicate]

Tags:

bash

I understand you can use echo for printing information on the console. But I've tried using return with integers and it didn't work very well for me.

As of

function echo_test() {
    echo 1;
}

function output_echo() {
    local result="$(echo_test)";

    if [[ ${result} == 1 ]]; then
        echo great;
    else
        echo nope;
    fi
}

Output "great", but:

function return_test() {
    return 1;
}

function output_return() {
    local result="$(return_test)";

    if [[ ${result} == 1 ]]; then
        echo great;
    else
        echo nope;
    fi
}

Did not work... and output "nope".

like image 434
Rafael Avatar asked Jan 03 '23 00:01

Rafael


1 Answers

You're conflating two separate things: output and exit status.

echo generates output. A command substitution like$(...) captures that output, but if you run a command without it, that output will go to the terminal.

return sets exit status. This is what's used to determine which branch is taken when running if your_function; then ..., or to populate $?.


To see your return_test function actually doing something, you could write:

return_test() {
    return 1;
}

return_test; echo "Exit status is $?"

Also, note that it's possible to do both:

myfunc() {
    echo "This is output"
    return 3
}

myfunc_out=$(myfunc); myfunc_rc=$?
echo "myfunc_out is: $myfunc_out"
echo "myfunc_rc is: $myfunc_rc"

...emits:

myfunc_out is: This is output
myfunc_rc is: 3

One useful idiom is to put an assignment inside an if condition, to branch on exit status while capturing output:

if myfunc_out=$(myfunc); then
  echo "myfunc succeeded (returned 0), with output: [$myfunc_out]"
else rc=$?
  echo "myfunc failed (nonzero return of $rc), with output: [$myfunc_out]"
fi

...which would, in this case, return:

myfunc failed (nonzero return of 3), with output: [This is output]

By the way, you may note that when the above code captures $?, it does so as close as possible to the command whose exit status is being captured, even when this means breaking normal conventions around vertical whitespace. This is intentional, to decrease the likelihood of added logging or other code changes inadvertently modifying $? between the point where it's set and where it's used.

like image 116
5 revs Avatar answered Jan 05 '23 17:01

5 revs