为何GPG命令输出无法用grep过滤或写入文件?
问题:GPG验证输出过滤与重定向异常问题
我想在GPG验证命令的输出中查找“AE09”并高亮对应行,原命令及输出如下:
~/Downloads$ gpg --verify sha256sum.txt.gpg sha256sum.txt gpg: Signature made Sun 18 Dec 2022 12:54:36 GMT gpg: using RSA key 27DEB15644C6B3CF3BD7D291300F846BA25BAE09 gpg: Good signature from "Linux Mint ISO Signing Key <root@linuxmint.com>" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 27DE B156 44C6 B3CF 3BD7 D291 300F 846B A25B AE09
尝试用grep过滤时,得到的是完整输出而非仅含“Primary key”的行:
~/Downloads$ gpg --verify sha256sum.txt.gpg sha256sum.txt | grep "AE09" gpg: Signature made Sun 18 Dec 2022 12:54:36 GMT gpg: using RSA key 27DEB15644C6B3CF3BD7D291300F846BA25BAE09 gpg: Good signature from "Linux Mint ISO Signing Key <root@linuxmint.com>" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 27DE B156 44C6 B3CF 3BD7 D291 300F 846B A25B AE09
尝试将输出重定向到文件,结果文件为空:
~/Downloads$ gpg --verify sha256sum.txt.gpg sha256sum.txt > res
使用--output参数也没解决问题:
~/Downloads$ gpg --output res --verify sha256sum.txt.gpg sha256sum.txt gpg: Signature made Sun 18 Dec 2022 12:54:36 GMT gpg: using RSA key 27DEB15644C6B3CF3BD7D291300F846BA25BAE09 gpg: Good signature from "Linux Mint ISO Signing Key <root@linuxmint.com>" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 27DE B156 44C6 B3CF 3BD7 D291 300F 846B A25B AE09
猜测GPG命令不是通过stdout输出内容,求解答。
解答
你的猜测完全正确,GPG默认会把验证过程的状态信息输出到标准错误流(stderr),而非标准输出流(stdout)。这就是为什么:
- 用
>重定向stdout时文件为空(因为内容根本没往stdout输出) grep只过滤stdout却能看到完整输出(因为stderr直接打印到终端,不受管道影响)
针对你的需求,提供几种解决方法:
1. 只保留含“AE09”的行
把stderr重定向到stdout,再用grep过滤:
gpg --verify sha256sum.txt.gpg sha256sum.txt 2>&1 | grep "AE09"
执行后会输出包含“AE09”的两行:
gpg: using RSA key 27DEB15644C6B3CF3BD7D291300F846BA25BAE09 Primary key fingerprint: 27DE B156 44C6 B3CF 3BD7 D291 300F 846B A25B AE09
2. 高亮输出中的“AE09”
如果要保留完整输出,仅高亮“AE09”,可以用grep的颜色高亮参数:
gpg --verify sha256sum.txt.gpg sha256sum.txt 2>&1 | grep --color=auto -E "(.*)?AE09(.*)?"
这样所有包含“AE09”的行里,该字符串会被终端高亮显示。
3. 将所有输出写入文件
要把GPG的所有输出(包括stderr)写入文件,需要同时重定向两个流:
# 写法1 gpg --verify sha256sum.txt.gpg sha256sum.txt > res 2>&1 # 写法2(更简洁) gpg --verify sha256sum.txt.gpg sha256sum.txt &> res
另外需要注意:GPG的--output参数是用来指定加密/解密后的文件内容输出路径,不是用来捕获命令本身的状态信息,所以之前用它无法解决问题。
内容的提问来源于stack exchange,提问作者Aubergine
相关产品推荐
相关产品推荐

