I'm trying to make a simple script to put my computer to sleep if it runs on battery unattended. I have this simple script:

if [ `cat /sys/class/power_supply/ADP1/online` -eq 0 ]; then
    cat /sys/class/power_supply/ADP1/online; # actual sleep command goes here

When I run it with xautolock -time 1 -noclose -locker /path/to/script.sh, it works as expected, printing zeroes every minute when the AC is disconnected, and sitting still if I move the mouse or connect the power adapter. So far so good.

However, for an unknown reason I fail to get this working as an one-liner:

xautolock -time 1 -noclose -locker "if [ `cat /sys/class/power_supply/ADP1/online` -eq 0 ]; then cat /sys/class/power_supply/ADP1/online; fi"

Here's a sample output:

0      # I start with the charger disconnected
0      # Here I connect the charger

As you can see, the value in /sys/class/power_supply/ADP1/online changes as expected, yet the condition seems to keep the initial value. Similarly, if I start the script with the AC power connected, nothing is ever printed in the terminal afterwards.

It looks like the command substitution is only evaluated the first time, and the output is reused afterwards. Is there a reasonable explanation as to why this is happening?

PS. I have tried the alternative substitution syntax $(), with the same results.


Yes, the command substitution is evaluated as soon as the xautolock command is parsed, as it's within double quotes.

You will have to put the if-statement in single quotes.

Personally, I would put the locker command in a separate script.

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.