1

I am a relatively experienced user in Linux. I want to understand better when it makes sense to use the pipe in Unix/Linux.

According to all book references, pipe | is used to connect commands together from left to right. When used with common commands such as ls, ps, echo, it is simple to understand that the pipe works very well because the previous commands produce simply an output without opening things such as a buffer viewer (e.g. less).

So if I execute ls | tr -d 'a', we all know things work. But if I execute top -n 1 | grep 'average', things start to come a little strange. In fact, if we use a screen oriented command left to the pipe, the pipe operator itself tries to redirect the output from that command and sometimes it is not easy to understand which kind of output redirects. I think this is due to a wrong usage of the pipe operator in such cases.

The question is: "When we should use the pipe operator and what happens if I try to use the pipe right to some commands like top and other screen oriented commands?"

Thank you.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • 1
    This might help: https://unix.stackexchange.com/questions/30759/whats-a-good-example-of-piping-commands-together – Andy Dalton Oct 24 '22 at 20:40

1 Answers1

1

The pipe operator (|) connects two commands (or command lists). The output (stdout) from the one on the left is attached to the input (stdin) of the one on the right. It is up to you to ensure that the output of the first is suitable for input to the second. Note that usually the error channel (stderr) is not redirected through the pipe and is written directly to the terminal from any process in the pipeline.

In the case of top, it assumes it's writing to a terminal in an interactive session. You can use the -b flag to tell it that it should assume a batch environment; this switches off the terminal positioning sequences, colour, and keyboard input.

top -b -n1 | grep average
top - 21:43:52 up 4 days,  9:49,  0 user,  load average: 0.00, 0.00, 0.00

Some commands, such as ls detect when they are writing directly to a terminal or some other output stream and modify their output appropriately. For example, in a directory with several files, compare ls and ls | cat.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287