user788171
user788171

Reputation: 17553

bash, nested commands and redirects

I am trying to track the CPU usage of a process using a command like this:

    top -b -d 1 | grep myprocess.exe

Next, I would like to redirect this to a log file, e.g.

    top -b -d 1 | grep myprocess.exe > output.log

Now, this does not actually work because it thinks I am grepping myprocess.exe > output.log instead of myprocess.exe

Does anybody know how I can get this redirect to work?

Upvotes: 4

Views: 1215

Answers (2)

Jo So
Jo So

Reputation: 26541

Now, this does not actually work because it thinks I am grepping myprocess.exe > output.log instead of myprocess.exe

Wrong. All should be fine. The 1st example executes the pipeline with stdout set to your terminal (thus you see the output, but nothing is written to the file). The 2nd example executes the pipeline with stdout set to output.log (thus you don't see output, but it will go right in your file).

If you want the output written to both, you need another process that gets your previous pipeline's stdout as stdin, and duplicates it. Like:

previous_pipeline | tee output.log

tee will print on stdout what it gets on stdin (So for stdout, everything is the same as before), but additionally open another file (given as cmdline arg) and write a copy to it.

Upvotes: 2

Blender
Blender

Reputation: 298582

Try tee:

top -b -d 1 | grep myprocess.exe | tee output.log

If you want it to show no output:

top -b -d 1 | grep myprocess.exe | tee output.log > /dev/null

Upvotes: 1

Related Questions