💻 Toggle screen blanking and screensaver on X11 from the terminal

I've been having an issue on i3wm that's been bugging me: the screen blanking doesn't get disabled with software like caffeine or stimulator. Both used to work but suddenly stopped, and I have no idea why.

Fortunately, there's xset to manage the screen blanking and screensaver from the terminal.

I wrote a function for my shell (zsh) to make it more interactive and easier to use. On a window manager, I can attribute keybindings to specific options to toggle the screen blanking and the screensaver or query their statuses, then get a notification about the change or the query.

The function is:

function XScreenManage {
		if ! command -v notify-send &> /dev/null; then
			echo -e "Warning: notify-send could not be found. Please install it using\
your distribution native package manager. On Arch Linux, you can install it\
with \"sudo pacman -Sy libnotify\""
			return 1 2>/dev/null
		fi


		local blanking() {
				blanking_status=$(xset s q | grep -i blanking | cut -d " " -f3-6)
				blanking_off="prefer blanking:  no"
				blanking_on="prefer blanking:  yes"

				if [[ $blanking_status = $blanking_off ]]; then
					echo -e "\n\e[0;93mEnabling screen blanking..."
					xset s blank
					xset s q | grep -i blanking | cut -d " " -f3-6
					notify-send "Screen blanking enabled"
				else
					echo -e "\n\e[0;93mDisabling screen blanking..."
					xset s noblank
					xset s q | grep -i blanking | cut -d " " -f3-6
					notify-send "Screen blanking disabled"
				fi
		}

		local screensaver() {
				screensaver_status=$(xset s q | grep -i timeout | cut -d " " -f3-5)
				screensaver_off="timeout:  0"
				screensaver_on="timeout:  600"

				if [[ $screensaver_status = $screensaver_off ]]; then
					echo -e "\n\e[0;93mEnabling screensaver..."
					xset s on
					xset s q | grep -i timeout | cut -d " " -f3-5
					notify-send "Screensaver enabled"
				else
					echo -e "\n\e[0;93mDisabling screensaver..."
					xset s off
					xset s q | grep -i timeout | cut -d " " -f3-5
					notify-send "Screensaver disabled"
				fi
		}

		local status() {
				notify-send "$(xset s q | grep -i blanking | cut -d " " -f2-6)"
				notify-send "$(xset s q | grep -i timeout | cut -d " " -f3-5)"
				xset s q | grep -i blanking | cut -d " " -f2-6
				xset s q | grep -i timeout | cut -d " " -f3-5
		}

		case "$1" in
				-b)
						blanking;;
				-s)
						screensaver;;
				-q)
						status;;
				-h | *)
						echo -e "-b\ttoggle screen blanking\n-s\ttoggle screensaver\n-q\t\
query screen blanking and screensaver status\n-h\tdisplay help"
		esac
}

I only tested them with zsh, as a function in my .zshrc, but it should work with bash and dash. It probably doesn't work in shells like fish, though. Also, you need notify-send, but the script throws an error and stops if it doesn't detect it in your $PATH.

This function is licensed under the CC0 1.0 license.

#Linux #X11 #Xset #WindowManager #i3wm