Why can't we direct these outputs into the file after route with Pipe?

You can understand much better what i mean by the example. In my example, why can't I route output with only the routing operator(">") without using the cat command?

With cat command:

└─$ whoami | cat > out.txt
└─$ cat out.txt

Without cat command:

└─$ whoami | > out1.txt
└─$ cat out1.txt
#no any content in file..
└─$ whoami | >> out2.txt
└─$ cat out2.txt
#no any content in file..

I could also use an alternative tool instead of the cat command. It's not the cat tool that's important here. What I want to ask is why can't we route data coming directly from the pipe with the routing operator ">"?

  • 1
    Flabergasted that is not a syntax error. But you do know you can simply do whoami > file, right? – Quasímodo Jan 9 at 16:06

The way a pipe works conceptually, is that it connects the output of the left command to the input of the right command.

So the line:

whoami | cat > out.txt

whoami will print to stdout by default but since there is a pipe it will get connected to the input of cat.

So what does this mean?

whoami | > out.txt

Well, you are saying attach the output of whoami to nothing. Then redirect the output of nothing to the file out.txt

The > operator means trunc the file named as the right argument, creating it if necessary, then redirect the output of the left command to the file. Note that

> out.txt

will create an empty file.

  • 1
    Any idea why whoami | ; errors out then? It is essentially the same without a redirection, if I'm reading your answer correctly. – Quasímodo Jan 9 at 16:10
  • @Quasímodo my guess would be that the | requires something to attach to on both sides. So A | ; doesn't have a right command, but A | > B does, the | can connect to the input of > but you would have to check the grammar to be sure. – user1794469 Jan 9 at 16:20
  • 1
    @Quasímodo Using "> Out.txt" is a valid procedure. But only ";" its use does not make sense for the shell. You can confirm this by entering both commands in your current console. When you use Pipe, A | B In the form of, processes A and B are executed in two separate subshells. Therefore, both processes A and B must be valid operations on the shell with alone. When only ";" the operator is used, we get an error because it does not make sense on the shell. – testter Jan 9 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.