Shell中管道Pipes的運用

You can connect processes using the pipe operator ( | ). In Linux, unlike in MS-DOS, processes connected by pipes can run simultaneously and are automatically rescheduled as data flows between them. As a simple example, you could use the sort command to sort the output from ps.

If you don’t use pipes, you must use several steps, like this:

$ ps > psout.txt

$ sort psout.txt > pssort.out

A much more elegant solution is to connect the processes with a pipe:

$ ps | sort > pssort.out

Because you probably want to see the output paginated on the screen, you could connect a third process, more, all on the same command line:

$ ps | sort | more

There’s practically no limit to the permissible number of connected processes. Suppose you want to see

all the different process names that are running excluding shells. You could use

$ ps –xo comm | sort | uniq | grep -v sh | more

This takes the name output of ps, sorts it into alphabetical order, extracts processes using uniq, uses grep –v sh to remove the process named sh, and finally displays it paginated on the screen.

 

However, be wary of one thing here: If you have a string of commands, the output file is created or written to immediately when the set of commands is created, so never use the same file-name twice in a string of commands. If you try to do something like cat mydata.txt | sort | uniq > mydata.txt you will end up with an empty file, because you will overwrite the mydata.txt file before you read it.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章