grep在测试TLS安全性时,我经常使用openssl结果.例如:
$ openssl s_client -tls1_2 -connect 172.11.15.32:443 </dev/null | grep 'IS s'
depth=0 C = US, ST = asd, O = Billing, CN = asdasd, emailAddress = root@asdasd
verify error:num=18:self signed certificate
verify return:1
depth=0 C = US, ST = asd, O = Billing, CN = asdasd, emailAddress = root@asdasd
verify return:1
DONE
Secure Renegotiation IS supported
Run Code Online (Sandbox Code Playgroud)
然而,问题是,无论我的grep是什么,输出始终包含这些(或类似的)行:
depth=0 C = US, ST = asd, O = Billing, CN = asdasd, emailAddress = root@asdasd
verify error:num=18:self signed certificate
verify return:1
depth=0 C = US, ST = asd, O = Billing, CN = asdasd, emailAddress = root@asdasd
verify return:1
Run Code Online (Sandbox Code Playgroud)
是否有可能以某种方式抑制这些消息并只接收grep结果?
如注释中所示,问题是该命令openssl显示其输出的一部分stderr.然后,无论你管道什么,这都会显示出来.
因此,如果您只想显示grep过滤给您的内容,您必须先重定向stderr到/dev/null这样才能"跳过管道":
openssl ... 2>/dev/null | grep 'IS s'
# ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
看另一个例子:
$ touch hello
$ ls hello adlsfjaskldf
ls: cannot access adlsfjaskldf: No such file or directory # stderr
hello # stdout
Run Code Online (Sandbox Code Playgroud)
让grep,出现一切:
$ ls hello adlsfjaskldf | grep hello
ls: cannot access adlsfjaskldf: No such file or directory # stderr
hello # stdout
Run Code Online (Sandbox Code Playgroud)
让我们grep但事先重定向stderr:
$ ls hello adlsfjaskldf 2>/dev/null | grep hello
hello # no "ls: cannot access..." here
Run Code Online (Sandbox Code Playgroud)