1

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.?

jimmij
  • 47,140
  • Realllly strongly related: https://unix.stackexchange.com/questions/159513/what-are-the-shells-control-and-redirection-operators; 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 01:47

2 Answers2

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.

jimmij
  • 47,140
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 >.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255