Section 43.1: 使用 |&

|& 将第一条命令的标准输出和标准错误连接到第二条命令,而 | 只将第一条命令的标准输出连接到第二条命令。

在本例中,页面是通过curl下载的。使用-v选项,curl会在stderr写入一些信息,包括,下载的页面会写入stdout。页面的标题可以在<title>和</title>之间找到。

curl -vs 'http://www.google.com/' |& awk '/Host:/{print}
/<title>/{match($0,/<title>(.*)<\/title>/,a);print a[1]}'

输出为

> Host: www.google.com
Google

但如果使用|,就会打印出更多信息,即那些被发送到stderr的信息,因为只有stdout会被传送到下一个命令。在本例中,除最后一行(Google)外,所有行都被 curl 发送到了 stderr:

* Hostname was NOT found in DNS cache
* Trying 172.217.20.228...
* Connected to www.google.com (172.217.20.228) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.35.0
> Host: www.google.com
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Sun, 24 Jul 2016 19:04:59 GMT
< Expires: -1
< Cache-Control: private, max-age=0
< Content-Type: text/html; charset=ISO-8859-1
< P3P: CP="This is not a P3P policy! See
https://www.google.com/support/accounts/answer/151657?hl=en for more info."
< Server: gws
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Set-Cookie: NID=82=jX0yZLPPUE7u13kKNevUCDg8yG9Ze_C03o0IMEopOSKL0mMITEagIE816G55L2wrTlQwgXkhq4ApFvvYEoaWFoEoq2T0sBTuQVdsIFULj9b2O8X35O0sAgUnc3a3JnTRBqelMcuS9QkQA;
expires=Mon, 23-Jan-2017 19:04:59 GMT;
path=/; domain=.google.com; HttpOnly
< Accept-Ranges: none
< Vary: Accept-Encoding
< X-Cache: MISS from jetsib_appliance
< X-Loop-Control: 5.202.190.157 81E4F9836653D5812995BA53992F8065
< Connection: close
<
{ [data not shown]
* Closing connection 0

Google

Section 43.2: 分页显示所有进程

ps -e | less

ps -e 显示所有进程,其输出通过 | 连接到 less 的输入,less 将结果分页。

Section 43.3: 修改命令的连续输出

~$ ping -c 1 google.com # unmodified output
PING google.com (16.58.209.174) 56(84) bytes of data.
64 bytes from wk-in-f100.1e100.net (16.58.209.174): icmp_seq=1 ttl=53 time=47.4 ms
~$ ping google.com | grep -o '^[0-9]\+[^()]\+' # modified output
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
64 bytes from wk-in-f100.1e100.net
...

管道 (|) 将 ping 的 stdout 连接到 grep 的 stdin,后者会立即处理这些数据。其他一些命令,如 sed 默认会对其 stdin 进行缓冲,这意味着它必须在收到足够的数据后才会打印任何内容,从而可能导致进一步处理的延迟。