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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值