Reputation: 65
Trying to write a bash script that will check for two mounted drives then do something if both are connected. So far I've got:
if [ $(mount | grep -c /media/card) != 1 ]
then
echo "ERROR: SD card not mounted"
sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
if [ $(mount | grep -c /media/backup) !=1 ]
then
echo "ERROR: Backup not mounted"
sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
echo "All Plugged in"
fi
fi
Running returns the error:
./backup2.sh: line 12: [: 0: unary operator expected
Not sure why the first if
statement works, but then the second doesn't, as they basically the same. Is there a cleaner way of checking for two mounted devices? Ideally outputting an error showing which one(s) aren't mounted.
Upvotes: 1
Views: 166
Reputation: 1628
This is a little cleaner code -- removed the nested if
and used elif
instead as well as taken into account janos
remark about the space needed at !=1
:
#!/bin/bash
if [ $(mount | grep -c /media/card) != 1 ]
then
echo "ERROR: SD card not mounted"
sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
elif [ $(mount | grep -c /media/backup) != 1 ]
then
echo "ERROR: Backup not mounted"
sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
echo "All Plugged in"
fi
Seems to work well under Red Hat 6.x
Upvotes: 0
Reputation: 124648
You need to put a space after the !=
:
if [ $(mount | grep -c /media/backup) !=1 ]
Like this:
if [ $(mount | grep -c /media/backup) != 1 ]
Btw, what happens if you have more than 1 mounted drives matching /media/card
or /media/backup
?
The output will be misleading,
saying that "X is not mounted".
So it seems it would make more sense to replace the != 1
conditions with == 0
.
But if you decide to do that,
then there's a better way to write the conditions,
using the exit codes of the pipelines directly.
if ! mount | grep /media/card >/dev/null
then
echo "ERROR: SD card not mounted"
sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
elif ! mount | grep /media/backup >/dev/null
then
echo "ERROR: Backup not mounted"
sudo sh -c "echo timer > /sys/class/leds/led0/trigger"
sudo sh -c "echo 2000 > /sys/class/leds/led0/delay_on"
else
echo "All Plugged in"
fi
Upvotes: 2