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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With