• Uncategorized

About bash : Echo-output-to-terminal-within-function-in-BASH

Question Detail

I am writing a script in BASH. I have a function within the script that I want to provide progress feedback to the user. Only problem is that the echo command does not print to the terminal. Instead all echos are concatenated together and returned at the end.

Considering the following simplified code how do I get the first echo to print in the users terminal and have the second echo as the return value?

function test_function {
    echo "Echo value to terminal"
    echo "return value"
}

return_val=$(test_function)

Question Answer

Yet a solution other than sending to STDERR (it may be preferred if your STDERR has other uses, or possibly be redirected by the caller)

This solution direct prints to the terminal tty:

function test_function {
    echo "Echo value to terminal" > /dev/tty
    echo "return value"
}

send terminal output to stderr:

function test_function {
    echo "Echo value to terminal" >&2
    echo "return value"
}

Dont use command substitution to obtain the return value from the function

The return value is always available at the $? variable. You can use the variable rather than using command substitution

Test

$ function test_function {
> return_val=10; 
> echo "Echo value  to terminal $return_val";
> return $return_val; 
> }

$ test_function
Echo value  to terminal 10

$ return_value=$?

$ echo $return_value
10

If you don’t know in which terminal/device you are:

function print_to_terminal(){
    echo "Value" >$(tty)
}

You may also like...

Leave a Reply

Your email address will not be published.

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