From 029e53a4339ed6209a550811cfd3ff9b93364494 Mon Sep 17 00:00:00 2001 From: John D Pell Date: Thu, 3 Mar 2022 23:37:37 -0800 Subject: [PATCH] plugin/battery: fix handling of multiple batteries with `upower` --- plugins/available/battery.plugin.bash | 12 ++++++------ test/plugins/battery.plugin.bats | 3 +-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/plugins/available/battery.plugin.bash b/plugins/available/battery.plugin.bash index 1f758e0cb5..b38d7f9d7b 100644 --- a/plugins/available/battery.plugin.bash +++ b/plugins/available/battery.plugin.bash @@ -4,8 +4,8 @@ about-plugin 'display info about your battery charge level' function ac_adapter_connected() { local batteries if _command_exists upower; then - batteries="$(upower -e | grep --max-count=1 -i BAT)" - upower -i "${batteries}" | grep 'state' | grep -q 'charging\|fully-charged' + IFS=$'\n' read -d '' -ra batteries < <(upower -e | grep -i BAT) + upower -i "${batteries[0]:-}" | grep 'state' | grep -q 'charging\|fully-charged' elif _command_exists acpi; then acpi -a | grep -q "on-line" elif _command_exists pmset; then @@ -20,8 +20,8 @@ function ac_adapter_connected() { function ac_adapter_disconnected() { local batteries if _command_exists upower; then - batteries="$(upower -e | grep --max-count=1 -i BAT)" - upower -i "${batteries}" | grep 'state' | grep -q 'discharging' + IFS=$'\n' read -d '' -ra batteries < <(upower -e | grep -i BAT) + upower -i "${batteries[0]:-}" | grep 'state' | grep -q 'discharging' elif _command_exists acpi; then acpi -a | grep -q "off-line" elif _command_exists pmset; then @@ -40,8 +40,8 @@ function battery_percentage() { local command_output batteries if _command_exists upower; then - batteries="$(upower --enumerate | grep --max-count=1 -i BAT)" - command_output="$(upower --show-info "${batteries:-}" | grep percentage | grep -o '[0-9]\+' | head -1)" + IFS=$'\n' read -d '' -ra batteries < <(upower -e | grep -i BAT) + command_output="$(upower --show-info "${batteries[0]:-}" | grep percentage | grep -o '[0-9]\+' | head -1)" elif _command_exists acpi; then command_output=$(acpi -b | awk -F, '/,/{gsub(/ /, "", $0); gsub(/%/,"", $0); print $2}') elif _command_exists pmset; then diff --git a/test/plugins/battery.plugin.bats b/test/plugins/battery.plugin.bats index 51ef93e944..96a0f58bcd 100755 --- a/test/plugins/battery.plugin.bats +++ b/test/plugins/battery.plugin.bats @@ -199,8 +199,7 @@ function setup_upower { function upower { case $1 in '-e'|'--enumerate') - # don't just `echo` twice because `grep` will close the pipe after matching the first line... - echo "$BAT0"$'\n'"/org/freedesktop/UPower/devices/mouse_hid_${RANDOM}_battery" + printf '%s\n' "$BAT0" "/org/freedesktop/UPower/devices/mouse_hid_${RANDOM}_battery" ;; '-i'|'--show-info') if [[ $2 == "$BAT0" ]]