The benefit is the current timestamp evaluated and attached to a message as the program writes it to the file. But note again that if the sed loop will die for some reason - your program will be blocked upon attempting to write to the file until someone will read from the fifo. If you can't configure it - simply delete the original log file and create a fifo file. The sed loop in the example above does nothing (sleeps) until you do echo.įor your particular situation you just configure your application to write log messages to the fifo file. If you want to read from a pipe the process will block until someone will write data to the pipe. If you try to write to a pipe the current process will block until someone would read data on the other side of the pipe. The important note is the fifo just as any other pipe has no sense if one of its sides is not connected to any process. > prints a message to its standard output redirected to the fifo file and sed receives it and processes and writes to a regular file. done runs an infinite loop and at every iteration it runs sed with redirecting to its standard input sed blocks in waiting for input data and then processes a received message and prints it to standard output redirected to foo.log.Īt this point you have to open a new terminal window because the loop occupies the current terminal.Įcho. # have to open a second terminal at this point $ while true do cat | sed -e "s/^/$(date -R) /" > foo.log done One program will write to the file and another will read data and receive it as the first sends. You can redirect it not just with | between commands in the script, but through a FIFO file (aka named pipe). The standard stream redirection described above called pipe. To avoid it you have to process messages as they are written to the file, not with a cron job. The current timestamp may be far from a moment when a message was generated. The problem is the $(date -R) evaluated once when you run the script so it will insert current timestamp to the beginning of each line. Then according to > bash redirects the output of sed to a file called output.log ( > means replace file contents and > means append to the end). The script "s/^/$(date -R) /" means replace every start of line to a text generated by date -R command (the general construction for replace command is: s/pattern/replace/). Sed reads data (as cat produces it), processes it (according to the script provided with -e option) and then prints it to its standard output. Normally the standard output is connected to a terminal, but this little script contains | so shell redirects the standard output of cat to standard input of sed. The General Way $ cat input.log | sed -e "s/^/$(date -R) /" > output.logĬat reads file called input.log and just prints it to its standard output stream.
0 Comments
Leave a Reply. |