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
oldstty=$(stty -g)
Ps=${1:-11}
stty raw -echo min 0 time 0
printf "\033]$Ps;?\033\"
sleep 0.1 read -r answer
result=${answer#*;} stty $oldstty
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/')"
r=$((16#${r})) g=$((16#${g})) b=$((16#${b}))
let "l=(2126${r} + 7152${g} + 722*${b})/10000" if [ $l -gt 128 ]; then DARKMODE=0 else DARKMODE=1 fi ```