2

the following code does not work properly and always prints the echo from the first elif. this is running on a bbb. would anyone be able to find the error i know its something stupid but i can't find it.

#!/bin/bash

#bashUSR.sh


path=/sys/class/leds/beaglebone:green:usr

echo "starting the LED bash script."

if [ "$#" == 0 ]; then
        echo "to few arguments. enter either 0 or 1 followed by on or off."
        exit 2

elif [ "$2" != "on" ] || [ "$2" != "off" ]; then
        echo "invalid second argument. please input either on or off."

elif [ "$1" == "0" ] && [ "$2" == "on" ]; then
        echo "turning on usr0 LED."
        export path0/brightness 1

elif [ "$1" == "0" ] && [ "$2" == "off" ]; then
        echo "turning off usr0 LED."
        export path0/brightness 0

elif [ "$1" == "1" ] && [ "$2" == "on" ]; then
        echo "turning on usr1 LED."
        export path1/brightness 1

elif [ "$1" == "1" ] && [ "$2" == "off" ]; then
        echo "turning off usr1 LED."
        export path1/brightness 0

else
        echo "invalid user number. please input a number between 0 and 1."
fi
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • As an aside -- when using `[ ]`, the only string comparison operator that it's good form to use is the one specified by POSIX, `=` (not `==`); see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Mar 07 '18 at 23:26

1 Answers1

1

Replace:

elif [ "$2" != "on" ] || [ "$2" != "off" ]; then
        echo "invalid second argument. please input either on or off."

With:

elif [ "$2" != "on" ] && [ "$2" != "off" ]; then
        echo "invalid second argument. please input either on or off."

Discussion

This logical test is always true:

[ "$2" != "on" ] || [ "$2" != "off" ]

Whatever the value of $2, one of the two tests above will be true. Because the two are connected with logical-or, the whole statement will be true.

I suspect that what you want is:

[ "$2" != "on" ] && [ "$2" != "off" ]

Example

Let's test this for three values of $2:

for x in on off other
do
    set -- 1 "$x"
    if [ "$2" != "on" ] && [ "$2" != "off" ]
    then
        echo "$2 is bad"
    else
        echo "$2 is OK"
    fi
done

The above code produces:

on is OK
off is OK
other is bad
John1024
  • 109,961
  • 14
  • 137
  • 171