views:

33

answers:

2

I want to redirect a bash script's output through a logging program. Specifically, Apache's logrotate utility. The redirection needs to be set within the script itself.

If the redirection were done on the command line, while executing the script, it would look like this:

myscript | logrotate -l $LOGFILE.%F 86400 2>&1

Here is some pseudo-code that goes inside the script to accomplish the output redirection, which does not work:

exec >(logrotate -l $LOGFILE.log.%F 86400) 2>&1
A: 

I don't think a script can redirect it's own output. Can you perhaps write a wrapper script for it though?

myscript:

myscript.real $@ | logrotate -l $LOGFILE.%F 86400 2>&1
zigdon
Use `"$@"` instead of `$*` to pass positional parameters to get proper quoting.
Roman Cheplyaka
Thanks, updated.
zigdon
Nope, it should be in double-quotes -- exactly as I wrote. `$@` without quotes is indeed no different from `$*` without quotes.
Roman Cheplyaka
+2  A: 

You can do that using a named pipe.

PIPE=/var/run/myscript/pipe
mkfifo "$PIPE"
logrotate -l "$LOGFILE.%F" 86400 < "$PIPE" &
exec > "$PIPE"

Also, regarding your 2>&1 redirection -- make sure you understand to what it is applied. In your first example it's applied to logrotate, while in the second "example" it would be applied to your script.

Roman Cheplyaka