Linux Shell – How to Redirect stdout & stderr to Logger

io-redirectionshellstdinstdout

I have a program I need to run at startup, it has output on stdout and stderr that I want to redirect to the system log using the logger command. What I have in my startup script is thie:

/home/dirname/application_name -v|logger 2>&1 &

This is redirecting the stdout to syslog just fine but stderr is coming to the console, so I need to refine the command.

Best Answer

You need to combine the output of STDERR and STDOUT prior to piping it to logger. Try this instead:

/home/dirname/application_name -v 2>&1 | logger &

Example

$ echo "hi" 2>&1 | logger &
[1] 26818
[1]+  Done                    echo "hi" 2>&1 | logger

$ sudo tail /var/log/messages
Apr 12 17:53:57 greeneggs saml: hi

You can use the abbreviated notation here as well, if used cautiously in a actual Bash shell (not to be confused with Dash):

$ echo "hi" |& logger &

NOTE: This is equivalent to <cmd1> 2>&1 | <cmd2>. Again only use the above when making use of an actual Bash shell interactively, would be a good way to approach it.

excerpt from ABSG

# |& was added to Bash 4 as an abbreviation for 2>&1 |.

References