Skip to content

Instantly share code, notes, and snippets.

@BobbyWibowo
Last active May 28, 2020
Embed
What would you like to do?
Backlight utility
#!/bin/bash
MAX_PATH="/sys/class/backlight/intel_backlight/max_brightness"
SET_PATH="/sys/class/backlight/intel_backlight/brightness"
MAX=$(cat $MAX_PATH)
CUR=$(cat $SET_PATH)
CURPERCENT=$(printf '%.2f' $(bc -l <<< "$CUR / $MAX * 100"))
printf '%s\n' "Backlight: $CUR/$MAX ($CURPERCENT%)"
#!/bin/bash
# This needs to echo into a system file.
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
INPUT=$1
if [ -z "$INPUT" ]; then
echo "No argument supplied."
exit 2
fi
if ! [[ "$INPUT" =~ ^[0-9]{1,3}(\+|-)?$ ]]; then
echo "Invalid input."
exit 3
fi
OPERATOR=${INPUT: -1}
if [[ "$OPERATOR" =~ ^(\+|-)$ ]]; then
INPUT=${INPUT::-1}
else
OPERATOR=""
fi
if [[ "$INPUT" -gt 100 ]] || [[ "$INPUT" -lt 0 ]]; then
echo "Invalid input."
exit 4
fi
# Paths.
MAX_PATH="/sys/class/backlight/intel_backlight/max_brightness"
SET_PATH="/sys/class/backlight/intel_backlight/brightness"
# Math.
MAX=$(cat $MAX_PATH)
OLD=$(cat $SET_PATH)
OLDPERCENT=$(bc -l <<< "$OLD / $MAX * 100")
printf 'Backlight: %d/%d (%.2f%%) -> ' $OLD $MAX $OLDPERCENT
# Some more math.
if [ "$OPERATOR" ]; then
if [ "$OPERATOR" = "+" ]; then
NEW=$(bc <<< "$OLD + ($MAX * $INPUT / 100)")
else
NEW=$(bc <<< "$OLD - ($MAX * $INPUT / 100)")
fi
else
NEW=$(bc <<< "$MAX * $INPUT / 100")
fi
# Make sure new value never goes out of bound.
if [[ "$NEW" -gt $MAX ]]; then
NEW=$MAX
elif [[ "$NEW" -lt 0 ]]; then
NEW="0"
fi
# A bit more math.
NEWPERCENT=$(bc -l <<< "$NEW / $MAX * 100")
printf '%d/%d (%.2f%%)\n' $NEW $MAX $NEWPERCENT
# Finally, set.
echo $NEW > $SET_PATH
@BobbyWibowo

This comment has been minimized.

Copy link
Owner Author

@BobbyWibowo BobbyWibowo commented May 28, 2020

set-backlight needs sudo. It's kinda annoying to use unless you put it into a sudoers file, e.g.

%sudo ALL=(root) NOPASSWD:/usr/local/bin/set-backlight

Usage:

set-backlight 0
set-backlight 25
set-backlight 100
set-backlight 15+
set-backlight 15-
get-backlight

Should be self-explanatory.

I'm using this with Openbox, to be added as shortcuts in Openbox's RC file.
I don't know how to otherwise set/get backlight level without root.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment