Joshua Swink
Joshua Swink

Reputation: 3450

How can you redirect a script's output through a process?

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

Upvotes: 5

Views: 1265

Answers (4)

MarcH
MarcH

Reputation: 19836

This is what you want:

exec  >  >(logrotate -l $LOGFILE.log.%F 86400)

Please see "process substitution" in Bash manual.

Please note that process substitution is not standard. The fallback is named pipes.

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 755114

The classic way to do this - in Bourne shell from Unix 7th Edition onwards - is:

{
...body of script here...
} | logrotate ...

If you want to redirect the errors too, then:

{
...body of script here...
} 2>&1 | logrotate ...

The only downside to this notation is the (often rather wide) separation between the start of the redirection and the end of it. From that point of view, the Bash process substitution is probably better if you're sure you'll have Bash available on all the relevant systems.

Upvotes: 0

zigdon
zigdon

Reputation: 15073

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

Upvotes: 0

Roman Cheplyaka
Roman Cheplyaka

Reputation: 38768

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.

Upvotes: 4

Related Questions