简体   繁体   中英

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

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?

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/bash

function print_message
{
    echo "message content"
}

print_message

$ ./yourscript
message content

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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM