Search code examples
bashshellraspberry-piraspbian

BASH script to check for two mounted drives 'unary operator expected'


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.


Solution

  • 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