I'm kind of confused about how Linux handles redirection operators.
I have in my home directory just one file:
andy$: ls
demo.mp4
Now, if I send the ls
output to a file, I should see only demo.mp4
in the file because there is nothing in the directory other than this file:
andy$: ls > myfile
But I actually noticed myfile
contains itself!
andy$ cat myfile
demo.mp4
myfile <-- ???
So this means that ls
gets executed after the creation of myfile
?
Something like:
- Create
myfile
- List directory content with
ls
- Write the content (now
myfile
exist) inmyfile
file
So in case I need to exclude the file I'm redirecting to I think I should do:
ls | grep -v "myfile" > myfile
So first, am I right?
If so, why? Where can I find more information on this?
2 Answers 2
Yes, you are right.
The shell performs redirection before running a command. When the shell runs a command, it sets up the new command’s standard input, output and error as appropriate. By default, they are connected to the terminal (or whatever the shell is connected to). When redirections are present, the relevant file descriptors are connected to the corresponding files (or pipes etc.). There is no buffering etc. — so the shell doesn’t accumulate a program’s output and then write it to a file; it connects the program’s output to the file and that deals with everything.
This means that the files need to be opened before the command is run.
You can find out more about this in the POSIX chapter on the shell language. The first section lists the sequence of operations the shell performs before running a command; you’ll see that redirection happens before command execution.
Since ls
is started with the open file as stdout, it is obvious that the file needs to be created before the ls
program is executed.
if you like to get more information, you may have a look at the POSIX standard for the shell: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sh.html
and the decription of the shell command language: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18