1

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:

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

fra-san
10.8k2 gold badges26 silver badges45 bronze badges
asked Jul 31, 2018 at 9:51

2 Answers 2

4

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.

answered Jul 31, 2018 at 10:19
1

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

answered Jul 31, 2018 at 10:17

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.