0

So I'm not sure why it's doing this. My if statement keeps interpreting the second variable as a literal string instead of a variable. Below is my exact code.

lights() {
  bulb1state=$(gatttool -b D8:6F:4B:09:AC:E6 --char-read -a 0x001b)
  echo $bulb1state
  bulb2state=$(gatttool -b DA:5A:4B:09:AC:E6 --char-read -a 0x001b)
  bulb3state=$(gatttool -b AC:E6:4B:07:39:E9 --char-read -a 0x0018)
  bulb4state=$(gatttool -b AC:E6:4B:08:40:50 --char-read -a 0x0018)
  offstate="Characteristic value/descriptor: 00 00 00 00"
  echo $bulb1state
  echo $offstate
  if [ "$offstate" = "$bulb1state" ]; then
    echo $bulb1state
    echo "bulb1 state = off"
    gatttool -b D8:6F:4B:09:AC:E6 --char-write -a 0x001b -n ff000000
    gatttool -b DA:5A:4B:09:AC:E6 --char-write -a 0x001b -n ff000000
    gatttool -b AC:E6:4B:07:39:E9 --char-write -a 0x0018 -n ff000000
    gatttool -b AC:E6:4B:08:40:50 --char-write -a 0x0018 -n ff000000
  fi
}  

My output:

>lights
Characteristic value/descriptor: 00 00 00 00
Characteristic value/descriptor: 00 00 00 00
Characteristic value/descriptor: 00 00 00 00

I don't understand why the last 2 echo statements are not displaying.

Edit: There was a white space on bulb1state. This is good enough for me to find a work around but I'm still curious as why the second term of the if statement was being interpreted as a literal string when I used the "=" operator as opposed to the "-eq" operator. It also didn't matter which variable was first or second.

  • Maybe there is an extra space at the end in the return string of gatttool (thus in $bulb1state). – agold Feb 2 '16 at 9:30
  • The arguments are treated as literal strings because that's what [ string1 = string2 ] does. The -eq operator, on the other hand, would treat them as integers. What were you expecting it to do? – Gordon Davisson Feb 3 '16 at 7:17
  • @GordonDavisson I'm expecting string2 to be evaluated as the value contained by $bulb1state not be evaluated as "$bulb1state". I know this is happening because my text editor, vim, changes the color of " $bulb1state" to the color of a string rather than the color of a variable. – RocketTwitch Feb 3 '16 at 8:54
0

Like I commented, you might have extra spaces in the output of gatttool (i.e. $bulb1state). For the comparison you should use = or == (which are equivalents), and for numbers -eq, see this answer. To ignore the extra spaces you can do (see this answer):

if [[ "$bulb1state" = "$offstate"* ]]; then
  #...
fi
  • Like I said, for some reason my second variable is being treated like a literal string. Using that exact statement still has this issue. I found a workaround but thank you for the white spaces comment. – RocketTwitch Feb 2 '16 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.