Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo output to terminal within function in BASH

Tags:

bash

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)
like image 721
McShaman Avatar asked Jan 05 '15 09:01

McShaman


People also ask

How do you echo in terminal?

To display the command prompt, type echo on. If used in a batch file, echo on and echo off don't affect the setting at the command prompt. To prevent echoing a particular command in a batch file, insert an @ sign in front of the command.

What is echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.


2 Answers

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"
}
like image 58
Robin Hsu Avatar answered Nov 08 '22 21:11

Robin Hsu


send terminal output to stderr:

function test_function {
    echo "Echo value to terminal" >&2
    echo "return value"
}
like image 21
Jasen Avatar answered Nov 08 '22 22:11

Jasen