Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe a process' output to logger command and to head command?

What I'm trying to do is:

  • Start a process that outputs text continously

  • Pipe that output to two commands:

    1. A logger script
    2. 'head' command, so I can save the first lines the initial process output.

What I tried so far (unsuccessfuly) is:

./myProgram | tee > (myLogger log.txt) | head > firstLines.txt

The problem is that the myProgram exits as soon as head is finished.

Even if I use -i in tee command, I can't get myProgram to keep running.

Since the logger may append the incoming text to an existing file, executing head log.txt > firstLines.txt won't work in this case.

like image 200
Stefano Avatar asked Jan 13 '16 13:01

Stefano


People also ask

How do you pipe the output of a command to a file?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

How do you send the output of one command into the input of another command in Linux?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

Which command operator pipes the output of one command as the input of another command?

One of the most powerful shell operators is the pipe ( | ). The pipe takes output from one command and uses it as input for another. And, you're not limited to a single piped command—you can stack them as many times as you like, or until you run out of output or file descriptors.


2 Answers

You can use awk as an alternative to do both:

./myProgram | 
    awk 'NR<=10{print > "firstLines.txt"} NR>10{close("firstLines.txt")} 1' > log.txt
like image 111
anubhava Avatar answered Oct 29 '22 07:10

anubhava


Like this maybe:

yes | awk 'FNR<4 {print >>"file"; close("file")}  1' | more

where yes is your program, file is where you send the output of head to, and more is your logger.

like image 23
Mark Setchell Avatar answered Oct 29 '22 08:10

Mark Setchell