Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

bash - Pipe | Redirection < > Precedence

I want to make clear when does pipe | or redirection < > takes precedence in a command?

This is my thought but 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 | ???
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...