0

I just started using bash recently and I'm having troubles with a simple command. Here's the script:

#!/bin/bash
if TouchpadOff=0; then 
    synclient TouchpadOff=1
    echo "Touchpad has been turned off"
else
    synclient TouchpadOff=0
    echo "Touchpad has been turned on"
fi

Basically, what I'm trying to do is toggle the pad to turn off or on depending on whether it is currently on or off. When the pad is on, running the script turns it off, which is what I want it to do.

But for some reason, when I run it again to turn the pad on, it is still turned off and still echos "Touchpad has been turned off", even when I want it to turn on. I hope someone can help me with my question. Thanks!

Byte Commander
  • 107,489

2 Answers2

3

The problem is your if-condition is wrong. It does not do what you think it does.

if TouchpadOff=0; then 

This runs TouchpadOff=0 as a shell command, which creates a variable $TouchpadOff and assigns it the value 0. As this should normally run successfully, the result is that the condition is always true.

You'll have to call the synclient command and parse its output to check the state of the TouchpadOff property, like e.g. this way:

if [[ "$(synclient | grep 'TouchpadOff' | awk '{print $3}')" -eq 0 ]] ; then

This will run synclient | grep 'TouchpadOff' | awk '{print $3}', which parses the output of synclient for a line containing "TouchpadOff" and returns the third column of that line.
It's inside a command substitution $( ... ), so that whole part will be substituted with the output of the inner command.
Then [[ ... -eq 0 ]] checks whether the substituted output is equal to 0 and makes that the condition for the if-statement.

Byte Commander
  • 107,489
  • Hi, Byte Commander, is there any special reason to use grep instead of awk '$1 ~ /^TouchpadOff$/ {print $3}'? – pa4080 Aug 31 '18 at 10:21
  • @pa4080 I think it's just habit. You could also avoid the regex and write awk '$1="TouchpadOff" {…}'. – PerlDuck Aug 31 '18 at 10:28
  • 1
    Thank you so much!!! This solved my problem straight away. I'm still new to bash so I didn't know about the variable thing. I really wanted to write the script by myself but I was forced to get help because of my inexperience. I won't fully leech off your answer though. I will research every aspect of the line you suggested such as the 'awk' part and figure out it's meaning. Thank you once again! – superdude Aug 31 '18 at 11:00
  • @PerlDuck right, could be done with pure awk of course. I just typed what came to my mind first and I thought would be the simplest to understand way. – Byte Commander Aug 31 '18 at 11:01
0

TouchpadOff=0 as a condition is interpreted as an assignment, so it's always true (unless the variable is readonly).

Use numeric comparison:

if (( TouchpadOff == 0 )) ; then
choroba
  • 9,643