Skip to content

Instantly share code, notes, and snippets.

@gentunian
Created July 1, 2018 06:33
Show Gist options
  • Save gentunian/5e8713af606dd6be613125d7b4d61c9b to your computer and use it in GitHub Desktop.
Save gentunian/5e8713af606dd6be613125d7b4d61c9b to your computer and use it in GitHub Desktop.
linux: set brightness using bash for later assign a key bind
#!/bin/bash
# Author: Sebastian Treu
# Date: 2018.06.01
#
# You will need root access for using this script. The best thing you can do
# is to add this script to the sudoers file (or just don't use it :)
#
usage() {
echo "Usage:"
echo -e "\t$0 { [+|-]threshold }"
echo
echo "Increase, decrease or set the brightness"
echo
echo "Example 1: Increase brightness +100 without exceeding max brightness value: ./brightness +100"
echo "Example 2: Set brightness to 100: ./brightness 100"
echo "Example 3: Decrease brightness by default increase threshold: ./brightness -"
}
# threshold argument must be passed
if [ $# -ne 1 ]; then
usage
exit 1
fi
# valid threshold argument is: (+|-)?[0-9]+
# i.e. +100, -30, 91, -, +
if ! $(echo ${1} | grep -q "^\(+\|-\)\?[0-9]*$"); then
usage
exit 1
fi
# Default threshold used when invoked "./brightness +"
DEFAULT_THRESHOLD=10
# Tune this path
BACKLIGHT_PATH=/sys/class/backlight/intel_backlight
BACKLIGHT_MAX_BRIGHTNESS_PATH=${BACKLIGHT_PATH}/max_brightness
BACKLIGHT_BRIGHTNESS_PATH=${BACKLIGHT_PATH}/brightness
# get the maximum brightness in order to not exceed that value
if [ -r ${BACKLIGHT_MAX_BRIGHTNESS_PATH} ]; then
MAX_BRIGHTNESS=$(cat ${BACKLIGHT_PATH}/max_brightness)
else
echo "Could not get MAX_BRIGHTNESS from ${BACKLIGHT_MAX_BRIGHTNESS_PATH}."
exit 1
fi
if [ -w ${BACKLIGHT_BRIGHTNESS_PATH} ]; then
case $1 in
+*|-*)
# this will strip of the minus or plus sign
OPERATION=${1:0:1}
# this will strip of the threshold value
THRESHOLD=${1:1}
# this will add or subtract the threshold and will use the default threshold if none supplied
VALUE=$(($(cat ${BACKLIGHT_PATH}/brightness) ${OPERATION} ${THRESHOLD:-${DEFAULT_THRESHOLD}}))
;;
*)
# no plus nor minus sign, set the threshold argument as the value
VALUE=${1}
;;
esac
# dont allow to exceed the max brightness
if [ ${VALUE} -ge ${MAX_BRIGHTNESS} ]; then
VALUE=${MAX_BRIGHTNESS}
fi
# set the brightness :)
echo ${VALUE} > ${BACKLIGHT_BRIGHTNESS_PATH}
else
echo "Could not set brightness."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment