sleep in Bash if/else sleep vs <condition> && sleep clamining cpu
0
votes
1
answer
1128
views
I wrote a script to check on the battery and if it is below 5% notify the user.
The script is put to sleep for 1 minute after every check.
If I write the script in the following way, the cpu workload will rise to great extend:
You can see in the image, that a lot of cpu resources are claimed. They will not be cleared.
If I write the script in a more conventional way, with simple if/else blocks, everything works as expected and the cpu will only go up for a short time in the beginning and after the sleep period is over:
#!/bin/sh
while true; do
[[
$(
upower -i /org/freedesktop/UPower/devices/battery_BAT0 |
grep percentage |
grep -Poe "\d*"
) -lt 5
]] &&
notify-send "Battery below 5%" &&
sleep 60
done
Do you know why the cpu went up?

while true; do
if [[
$(
upower -i /org/freedesktop/UPower/devices/battery_BAT0 |
grep percentage |
grep -Poe "\d*"
) -lt 5
]]; then
notify-send "Battery below 5%"
else
sleep 60
fi
done
Do you know why this behaviour is happening?
Asked by jeykey
(33 rep)
Jul 13, 2022, 06:22 PM
Last activity: Jul 13, 2022, 07:13 PM
Last activity: Jul 13, 2022, 07:13 PM