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

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


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.


You are explicitly saying "don't print the output directly! Put it in a variable so I can print it myself!".

You can simply stop doing that, and the message will be printed automatically:

$ cat yourscript #!/bin/bashfunction print_message{    echo "message content"}print_message$ ./yourscriptmessage content


Invoking print_message inside $(...) redirects the output. If you don't want the output redirected then invoke the command without the $(...). E.g.

 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.

Note, the return value from the function you provided will now be the name of the function.