gpt4 book ai didi

bash - 将 grep 结果保存到变量

转载 作者:行者123 更新时间:2023-12-05 08:34:31 25 4
gpt4 key购买 nike

我有以下命令:

pvs /dev/sdb | grep failed

结果例如:

/dev/sdb: read failed after 0 of 4096 at 0: Input/output error
/dev/sdb: read failed after 0 of 4096 at 1073676288: Input/output error
/dev/sdb: read failed after 0 of 4096 at 1073733632: Input/output error
/dev/sdb: read failed after 0 of 4096 at 4096: Input/output error

现在我想将该结果保存到一个变量中:

STATUS=`pvs /dev/sdb | grep failed`

但是,当我阅读内容时,它是空的:

echo $STATUS

我尝试将它重定向到一个文件:

`pvs /dev/sdb | grep failed` > /tmp/hdd-status

同样的结果,文件仍然是空的。

最佳答案

您看到的消息似乎是标准错误 消息,而不是标准输出。您可以阅读有关重定向的更多信息 here .

因此,在将输出管道输出到 grep 之前,您需要将 STDERRSTDOUT 合并:

STATUS=`pvs /dev/sdb 2>&1 | grep failed`

此外,command substitution 的另一种形式而不是使用反引号更具可读性:

STATUS=$(pvs /dev/sdb 2>&1 | grep failed)

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

关于bash - 将 grep 结果保存到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com