How does (echo 'text' ; cat file.txt ) > new file.txt actually work?
Solution 1
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.
Solution 2
The shell picks up that command line in three parts:
(echo ...
)>
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 >
.
Simullacra
Updated on September 18, 2022Comments
-
Simullacra over 1 year
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.?-
Jeff Schaller almost 6 yearsRealllly strongly related: unix.stackexchange.com/questions/159513/…; the key element is the
>
-
smw almost 6 years"How exactly does it redirect the output of echo to cat" it doesn't - it redirects the outputs of both
echo
andcat
tofile.txt
-
muru almost 6 years"does it redirect the output of echo to cat" .. it doesn't.
-