J.Doe
J.Doe

Reputation: 61

Why does a bash redirection happen *before* the command starts, if the ">" is after the command?

Recently I tried to list all of the images located in a directory I had (several hundred) and put them into a file. I used a very simple command

ls > "image_names.txt"

I was bored and decided to look inside the file and realized that image_names.txt was located in the file. Then I realized, the order of operations performed was not what I thought. I read the command as left to right, in two separate steps:

  1. ls (First list all the file names)
  2. > "image_names.txt" (Then create this file and pipe it here)

Why is it creating the file first then listing all of the files in the directory, despite the ls command coming first?

Upvotes: 5

Views: 145

Answers (2)

Logan Lee
Logan Lee

Reputation: 997

Because redirection > "image_names.txt" was performed before ls command.

Upvotes: 0

awiebe
awiebe

Reputation: 3836

When you use output redirection, the shell needs a place to put your output( suppose it was very long, then it could all be lost on terminate, or exhaust all working memory), so the first step is to open the output file for streaming output from the executed command's stdout.

This is especially important to know in this kind of command

cat a.txt | grep "foo" > a.txt

since a is opened first and not in append mode it will be truncated, meaning there is no input for cat. So the behaviour you expect that the lines will be filtered from a.txt and replace a.txt will not actually happen. Instead you will just lose the contents of a.txt.

Upvotes: 2

Related Questions