A Line By Line Explanation of The Bash Script For Scheduling Night Mode For A Better Screen Viewing

Introduction
In my previous post on here, I wrote a bash script for scheduling night mode on devices for better viewing. Now, I will be explaining line by line what the script entails.
#!/bin/bash
CONFIG_FILE="$HOME/.nightmode.conf"
TEMP_DAY=6500 # Default daytime temperature (neutral white)
TEMP_NIGHT=3500 # Night temperature (warm yellow/red)
TRANSITION_TIME=60 # Transition duration in seconds
# Load or initialize config
load_config() {
if [ -f "$CONFIG_FILE" ]; then
source "$CONFIG_FILE"
else
ENABLED=false
CURRENT_TEMP=$TEMP_DAY
save_config
fi
}
save_config() {
echo "ENABLED=$ENABLED" > "$CONFIG_FILE"
echo "CURRENT_TEMP=$CURRENT_TEMP" >> "$CONFIG_FILE"
}
# Adjust screen temperature
set_temperature() {
local temp=$1
local transition=$2
for output in $(xrandr --current | grep " connected" | cut -d' ' -f1); do
xrandr --output "$output" --gamma 1:1:1 --brightness 1.0
if [ "$transition" -gt 0 ]; then
xrandr --output "$output" --gamma 1:0.8:0.7 --brightness 0.9 \
--transition "$TRANSITION_TIME"
fi
done
CURRENT_TEMP=$temp
save_config
}
# Main control functions
start_nightmode() {
if [ "$ENABLED" = false ]; then
set_temperature "$TEMP_NIGHT" "$TRANSITION_TIME"
ENABLED=true
echo "Night mode activated (Temperature: $TEMP_NIGHT K)"
else
echo "Night mode is already running!"
fi
}
stop_nightmode() {
if [ "$ENABLED" = true ]; then
set_temperature "$TEMP_DAY" "$TRANSITION_TIME"
ENABLED=false
echo "Night mode deactivated (Temperature: $TEMP_DAY K)"
else
echo "Night mode is not active!"
fi
}
check_status() {
if [ "$ENABLED" = true ]; then
echo "Night mode is ON (Current temp: $CURRENT_TEMP K)"
else
echo "Night mode is OFF (Daytime temp: $CURRENT_TEMP K)"
fi
}
# Parse command-line arguments
case "$1" in
"start")
load_config
start_nightmode
;;
"stop")
load_config
stop_nightmode
;;
"status")
load_config
check_status
;;
*)
echo "Usage: $0 [start|stop|status]"
exit 1;;
esac
Line 1
Shebang specifies that the script should run on bash.
Line 2
The “CONFIG_FILE“ sets the path where the directory will be saved.
Line 3
The variables are used to set color temperature in Kelvin and transition duration in seconds.
Line 4-8
The if statement checks if the configuration file exists, else it saves the variables into the file. The next line writes the current state to the configure line.
Line 9-12
The next few lines smoothly changes the temperature over specificed time, updates the CURRENT_TEMP and saves the config.
Line 13-24
The next few lines activates the night mode if not already enabled and reverts to daytime setting if night mode was active. It also reports current mode and temperature.
Line 25-72
The few last lines uses the case statement and also uses the exit code to validate if the previous commands were successful.
Subscribe to my newsletter
Read articles from Ojukwu Ebube directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
