-1

I'm kind of confused on the sequence Linux handles Redirection Operator.

I have in my home 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?

Somehting like:

  1. Create myfile
  2. List directory content with ls
  3. Write the content (now myfileexist) in myfile file

So in case I need to exclude self I think I should:

ls | grep -v "myfile" > myfile

So first, am I right?

If so, WHY!? Where can I find more infos on this?

3

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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