0

bash-newbie here.

I want to use the following simple script as a shortcut to enable/disable the touchpad of my laptop:

#!/bin/bash

result=$(xinput --list-props 11 | grep "Device Enabled")
echo $result
# Output: Device Enabled (140): 1

if [[ "$result" = "Device Enabled (140): 1" ]]; then
        `xinput set-prop 11 "Device Enabled" 0`
else
        `xinput set-prop 11 "Device Enabled" 1`
fi

The if-condition is however never entered. echo $result shows that the variable really contains the string-value that I want to compare. I have been searching for a while but can not at all figure out why the result-variable and the string do not match in the if-condition.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
zet0x
  • 21
  • 3
  • 3
    Please take a look: http://www.shellcheck.net/ – Cyrus Oct 14 '17 at 19:44
  • Replace `echo $result` by `echo "$result"`. There are two tabs in your variable. – Cyrus Oct 14 '17 at 19:51
  • do you really have your conditional use of `xinput` surrounded in back-quotes? If you want to display the output of those commands, you need to use something like `echo ` to preceed them. AND as you're already using the `$( cmd )` form of cmd-substitution, do so also for these lines. I'm guessing you don't really need cmd-substitution for your conditional use of `xinput ...`, . Will be interested to see if `shellcheck.net` flags that. (yep, it does). Good luck. – shellter Oct 14 '17 at 19:55
  • Thank you. `echo "$result"` made me aware that there is a tab character preceding the string obtained by grep. – zet0x Oct 14 '17 at 20:02

2 Answers2

1

The string obtained by grep has a tab at the beginning, which needed to be included in the compared string. Checking again with echo "$result" (with added quotation marks) helped.

zet0x
  • 21
  • 3
0

In bash (but not more basic shells), you can use [[ ]]'s pattern matching capabilities to check whether a string contains a pattern; using it this way removes the need to worry about leading tabs, or even the need to use grep to pick out the relevant line:

if [[ "$(xinput --list-props 11 | grep "Device Enabled")" = *"Device Enabled (140): 1"* ]]; then

Note that the *s at the beginning and end of the pattern mean "preceded by anything" and "followed by anything" respectively.

Also, the double-quotes around $(xinput ...) aren't really necessary here, but IMO keeping track of which places are safe to leave double-quotes off and when it's not safe is too much trouble. (The left side of an = comparison inside [[ ]] is one of the safe places, but the right side isn't, and in [ ] it's almost never safe -- good luck remembering all that correctly!) So I prefer to just always use double-quotes.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151