How can you redirect script output through a process?

I want to redirect the output of a bash script through a logging program. In particular, the logrotate Apache utility. Redirection must be set inside the script itself.

If the redirection was done on the command line, when running the script, it would look like this:

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

Here is some pseudo code that goes into the script to redirect output that doesn't work:

 exec >(logrotate -l $LOGFILE.log.%F 86400) 2>&1 
+4
source share
4 answers

You can do this using a named pipe.

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

Also, regarding the redirection 2> and 1 - make sure you understand what this applies to. In the first example, this applies to logrotate, and in the second "example" it will be applied to your script.

+4
source

Is this what you want:

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

See "Process Replacement" in the Bash manual.

Please note that process replacement is not standard. The return is called pipe.

+3
source

I do not think the script can redirect its own output. Can you possibly write a wrapper script for this?

MyScript:

 myscript.real " $@ " | logrotate -l $LOGFILE.%F 86400 2>&1 
0
source

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

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

If you also want to redirect errors, follow these steps:

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

The only drawback of this notation is the (often fairly wide) separation between the start of the redirect and its end. From this point of view, replacing the Bash process is probably better if you are sure that you will have Bash available on all relevant systems.

0
source

All Articles