Veracious Network More than just a game, it's a community!

Bash Auto-Dark Mode Script

Simple script to detect the terminal background color and calculate the luminance of that compared to straight black or white. Useful for displaying different colors in a script based on a light or dark background.

```bash

Detect shell background color to know which to use for foreground colors

https://gist.github.com/blueyed/c8470c2aad3381c33ea3

oldstty=$(stty -g)

What to query?

11: text background

Ps=${1:-11}

stty raw -echo min 0 time 0

stty raw -echo min 0 time 1

printf "\033]$Ps;?\033\"

xterm needs the sleep (or "time 1", but that is 1/10th second).

sleep 0.1 read -r answer

echo $answer | cat -A

result=${answer#*;} stty $oldstty

Extract individual colors

r="$(echo $result | sed 's/rgb:([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]\/([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]\/([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]./\1/')" g="$(echo $result | sed 's/rgb:([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]\/([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]\/([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]./\2/')" b="$(echo $result | sed 's/rgb:([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]\/([0-9a-f][0-9a-f])[0-9a-f][0-9a-f]\/([0-9a-f][0-9a-f])[0-9a-f][0-9a-f].*/\3/')"

Convert to dec

r=$((16#${r})) g=$((16#${g})) b=$((16#${b}))

https://en.wikipedia.org/wiki/Luminance_%28relative%29

let "l=(2126${r} + 7152${g} + 722*${b})/10000" if [ $l -gt 128 ]; then DARKMODE=0 else DARKMODE=1 fi ```