Shell – Behaviour of “|” pipe in linux with “>” output redirection

io-redirectionpipeshell

I am executing command

ls > a.txt | sort > b.txt

This command is doing the below things :

  1. executing ls

  2. sorting it

  3. creating a.txt and storing sorted output to a.txt

  4. creating b.txt , but its empty.

Can anyone explain this ?

I am implementing my own shell for which I need to understand this behavior & simulate it.

Best Answer

The | will take the output of the command on the left and give it to the input of the command on the right. The > operator will take the output of the command and put it into a file. That means, in your example, by the time it gets to the | there is no output left; it's all gone into a.txt. So the sort on the right operates on an empty string and saves that to b.txt

What you would probably like is to use the tee command which will both write to a file and stdout like

ls | tee a.txt | sort > b.txt

Though I'm really curious what you're trying to do, since ls can/will sort things for you as well.

Related Question