$ ls > ls.out cause 'ls.out' to be included in list of names of files in current directory? Why was this chosen to be? Why not otherwise?
When evaluating the command the
This is also the reason why reading and writing to the same file using a
Tricks to avoid this:
On why redirections are resolved before the program / script / whatever is run, I don't see a specific reason why it's mandatory to do so, but I see two reasons why it's better to do so:
So a waste of time in the first case and a waste of time and memory in the second case.
This is just what occurs to me, I'm not claiming these are the actual reasons; but I guess that all in all, if one had a choice, they would go with redirecting before anyway for the abovementioned reasons.
First sentence, suggests that output is made to go somewhere other than
To avoid having a file, I suggest you redirect output to named pipe first, and then to file. Note the use of
Think about this - where will be the output ? A program has functions like
I don't disagree with the current answers. The output file has to be opened before the command runs or the command won't have anywhere to write its output.
This is because "everything is a file" in our world. Output to screen is SDOUT (aka file descriptor 1). For an application to write to the terminal, it opens fd1 and writes to it like a file.
When you redirect an application's output in a shell, you're altering fd1 so it's actually pointing at the file. When you pipe you alter one application's STDOUT to become another's STDIN (fd0).
But it's all nice saying that, but you can quite easily look at how this works with
This is a bit of juggling. We shunt STDOUT (fd1) off to fd10 and close it off. This is because we're not outputting anything to the real STDOUT with this command. It finishes by duplicating the write handle to
This is it searching for the executable. A lesson perhaps to not have a long path ;)
Then the command runs and the parent waits. During this operation any STDOUT will have actually mapped to the open file handle on
Why is there so much juggling? No I'm not entirely sure either.
Of course you can change this behaviour. You could buffer to memory wth something like
There is also a nice article about Implementation of redirection and pipe operators in shell. Which shows how redirection could be implemented so