Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving grep's result to a variable

Tags:

grep

bash

I have the following command:

pvs /dev/sdb | grep failed

The result is for example:

/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

Now I want to save that result to a variable:

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

However, when I read the content, it is empty:

echo $STATUS

I tried redirecting it to a file:

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

Same result, the file remains empty.

like image 833
Sheriff Hobbes Avatar asked Apr 30 '26 22:04

Sheriff Hobbes


1 Answers

The messages that you see appear to be standard error messages, not standard output. You can read more about redirection here.

As such, you'd need to merge STDERR with STDOUT before piping the output to grep:

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

Moreover, the other form of command substitution instead of using backticks is somewhat more readable:

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.

like image 70
0xdeadbeef Avatar answered May 03 '26 19:05

0xdeadbeef