How do I echo directly on standard output inside a shell function?

Aracthor picture Aracthor · Jul 27, 2015 · Viewed 51.6k times · Source

I, in my script, shell a function that prints a message on the console. It can be called from any other function.

function print_message
{
    echo "message content"
}

The problem is, in shell, functions like echo or printf that usually print data on standard output redirect their messages to the calling function instead as a return value.

return_value=$(print_message) # this line print nothing.
echo $return_value # This line print the message. I don't want to have to do it.

I would like to avoid this behavior and print it directly on standard - or error - output. Is there a way to do it?

Or am I just wrong to want to use functions in shell, and should I use instead a huge script to handle any comportment?

Answer

Etan Reisner picture Etan Reisner · Jul 27, 2015

The $(...) calling syntax captures standard output. That is its job. That's what it does.

If you want static messages that don't get caught by that then you can use standard error (though don't do this for things that aren't error message or debugging messages, etc. please).

You can't have a function which outputs to standard output but that doesn't get caught by the $(...) context it is running in because there's only one standard output stream. The best you could do for that would be to detect when you have a controlling terminal/etc. and write directly to that instead (but I'd advise not doing that most of the time either).

To redirect to standard error for the function entirely you can do either of these.

print_message() {
    echo "message content" >&2
}

or

print_message() {
    echo "message content"
} >&2

The difference is immaterial when there is only one line of output but if there are multiple lines of output then the latter is likely to be slightly more optimized (especially when the output stream happens to be a file).

Also avoid the function keyword as it isn't POSIX/spec and isn't as broadly portable.