ygoe
ygoe

Reputation: 20384

Bash: if (command) |(command)

I know that the following command returns 0 (true) or 1 (false) in the following conditions:

hdparm -C /dev/sda |grep "active/idle"

true if the disk is active, false otherwise. I'd like to programmatically use this result to display another text or use it for monitoring. I've tried with this, but it doesn't work (syntax error):

if [ hdparm -C /dev/sda |grep "active/idle" ]; then
    echo sda1 is ON
else
    echo sda1 is OFF
fi

How does it work correctly?

Also, is there a clearly understandable, definitive guide on Bash conditional expressions somewhere that would explain all the different kinds of expression statements for every possible situation?

Upvotes: 1

Views: 193

Answers (2)

choroba
choroba

Reputation: 241878

I usually just simply use

if hdparm -C /dev/sda | grep -q 'active/idle' ; then
    echo sda1 is ON
else
    echo sda1 id OFF
fi

Upvotes: 3

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

Wrap the conditional statement inside a subshell:

if [ -z "$(hdparm -C /dev/sda |grep "active/idle")" ]; then

-z tests the empty string here. Probably you also have to replace active/idle with active.

EDIT: as @abasu suggests, in this case, it's better to test for the return code of grep, which will be 0 if the expression was matched:

hdparm -C /dev/sda | grep -q "active/idle"
status=$?
if [ $status -eq 0]; then

You will find all details on conditional statements on test man page. However, your shell may expand the syntax further, like bash does.

Upvotes: 1

Related Questions