将grep的结果保存到变量中

时间:2014-08-21 12:00:42

标签: bash grep

我有以下命令:

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

同样的结果,文件仍为空。

2 个答案:

答案 0 :(得分:5)

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

因此,在将输出汇总到STDERR之前,您需要将STDOUTgrep合并:

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

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

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

当使用旧式反引号替换形式时,反斜杠   保留其字面含义,除非后跟$,`或\。   第一个不带反斜杠的反引号终止命令   代换。使用$(命令)表单时,所有字符之间   括号组成命令;没有人受到特别对待。

答案 1 :(得分:4)

这是因为您看到的内容来自stderr,而您只是stdin

只需将stderr重定向到stdin:

2>&1

这样你的变量定义如下:

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

另请注意,我使用$()语法,这通常比``更受欢迎。基本上,因为它允许你嵌套它们。


见另一个例子:

我们ls两个文件:ahello。首先存在,但hello不存在:

$ ls a hello
ls: cannot access hello: No such file or directory
a

我们存储输出:

$ v=$(ls a hello)
ls: cannot access hello: No such file or directory

错误未存储:

$ echo "$v"
a

但是,如果我们重定向:

$ v=$(ls a hello 2>&1)
$ echo "$v"
ls: cannot access hello: No such file or directory
a