1

This question already has an answer here:

So, here's a simple code:

(echo "Some text to prepend"; cat gero.txt) > file.txt

And I can't really grasp the mechanics of this code. So basically gero.txt is an already existing file, we create a new file.txt with "Some text to prepend"+gero.txt The thing I don't get is that part in parentheses. How exactly does it redirect the output of echo to cat with no evident operator like pipe | etc.?

marked as duplicate by G-Man, Rui F Ribeiro, Gilles bash Jun 20 '18 at 6:28

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Realllly strongly related: unix.stackexchange.com/questions/159513/…; the key element is the > – Jeff Schaller Jun 19 '18 at 22:16
  • 1
    "How exactly does it redirect the output of echo to cat" it doesn't - it redirects the outputs of both echo and cat to file.txt – steeldriver Jun 19 '18 at 22:32
  • "does it redirect the output of echo to cat" .. it doesn't. – muru Jun 20 '18 at 1:47
4

When you run a sequence of commands in the interactive shell, like

echo xxx; cat file; ls; echo yyy

then everything is executed consecutively and the output is send to the terminal.

But, if you run these commands inside parenthesis () a new non-interactive shell is created and everything is executed inside it. Now, with >file.txt after () you redirect the whole output from this hidden sub-shell to a file.

1

The shell picks up that command line in three parts:

  1. (echo ...)
  2. >
  3. file.txt

The (standard) output -- not any stderr output -- from part #1 is redirected by part #2 into the file given in part #3. The parenthesis in part one simply groups all of the output together for the redirection operator >.

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