首页 > 解决方案 > 为什么我在发送标准输出后有一个空文件

问题描述

使用 bash 我正在执行以下命令来过滤证书中的信息

openssl s_client -connect google.com:443 < /dev/null > cert.pem 
openssl x509 -in cert.pem -noout -subject > commonName
tr "," "\n" < commonName | sed -nr '/CN/p' | tr -d ' /t' > commonName

最后一个命令将文件“commonName”留空,我想知道这是为什么。如果我改为附​​加文件“>>”,则会显示所需的过滤输出,但保留未过滤的内容。

将文件留空

tr "," "\n" < commonName | sed -nr '/CN/p' | tr -d ' /t' > commonName

有效,但内容不受欢迎

tr "," "\n" < commonName | sed -nr '/CN/p' | tr -d ' /t' >> commonName

编辑,可能会添加发送到具有新名称的文件按预期工作。例如,将“commonName”更改为“test”。

提前致谢!/R

标签: bashsedfilterstdouttr

解决方案


您不能使用其他命令编辑文件,并且只能在一个管道中使用 sed(您的操作方式)。您需要一个临时文件:

openssl s_client -connect google.com:443 < /dev/null > cert.pem 
openssl x509 -in cert.pem -noout -subject > commonName
tr "," "\n" < commonName | sed -nr '/CN/p' | tr -d ' /t' > /tmp/temp
mv /tmp/temp commonName

还有一个更好的方法来实现整个脚本,没有临时文件:

openssl s_client -connect google.com:443 < /dev/null > cert.pem 
openssl x509 -in cert.pem -noout -subject |
    tr "," "\n" |
    grep -o 'CN .*' > commonName

推荐阅读