r/bash • • 17d ago

critique am I using pkexec properly in this script?

/r/linuxquestions/comments/1xrtrff/am_i_useing_pkexec_properly_in_this_script/
1 Upvotes

1 comment sorted by

1

u/bac0on 16d ago edited 15d ago

Just a small pointer — you presume that if status_check isn't 1, it has to be 0 ...
Instead, you could sanitize status_check and use an array. That would get rid of the if-then statement altogether:

declare -a on_off=(off on)

[[ $status_check = [0-1] ]] || \
    exit 1
status_mode=${on_off[status_check]} option=${on_off[status_check ^ 1]}

You can flip the "bit" much in the same way: $((t ^= 1)) or $((t = !t))

toggle () {
    local -i t=$1
    echo "toggle: $((t ^= 1))"
    pkexec echo "$t" > /sys/bus/platform/drivers/ideapad_acpi/VPC2004\:00/conservation_mode
}

It's almost better to use specifiers in the format argument. \ evaluates in double quotes, which will break your newline, so "Turn $option\nReturn" becomes "Turn \\nReturn" if ever $option contain a \.

printf 'Turn %s\nReturn' "$option"