bashunixredirectcommandpipe

Pipe | Redirection < > Precedence


I want to make clear: When does pipe | or redirection < > take precedence in a command?

This is my thought but I need confirmation this is how it works.

Example 1:

sort < names | head

The pipe runs first: names|head then it sorts what is returned from names|head

Example 2:

ls | sort > out.txt

This one seems straight forward by testing, ls|sort then redirects to out.txt

Example 3:

Fill in the blank? Can you have both a < and a > with a | ???


Solution

  • In terms of syntactic grouping, > and < have higher precedence; that is, these two commands are equivalent:

    sort < names | head
    ( sort < names ) | head
    

    as are these two:

    ls | sort > out.txt
    ls | ( sort > out.txt )
    

    But in terms of sequential ordering, | is performed first; so, this command:

    cat in.txt > out1.txt | cat > out2.txt
    

    will populate out1.txt, not out2.txt, because the > out1.txt is performed after the |, and therefore supersedes it (so no output is piped out to cat > out2.txt).

    Similarly, this command:

    cat < in1.txt | cat < in2.txt
    

    will print in2.txt, not in1.txt, because the < in2.txt is performed after the |, and therefore supersedes it (so no input is piped in from cat < in1.txt).