Search code examples
unixterminalx11gnome-terminal

How to determine a terminal's background color?


I'd like to know if there is any way to determine a terminal's background color ?

In my case, using gnome-terminal.
It might matter, since it's entirety up to the terminal application to draw the background of its windows, which may even be something else than a plain color.


Solution

  • I've came up with the following:

    #!/bin/sh
    #
    # Query a property from the terminal, e.g. background color.
    #
    # XTerm Operating System Commands
    #     "ESC ] Ps;Pt ST"
    
    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.00000001
    read -r answer
    # echo $answer | cat -A
    result=${answer#*;}
    stty $oldstty
    # Remove escape at the end.
    echo $result | sed 's/[^rgb:0-9a-f/]\+$//'
    

    Source/Repo/Gist: https://gist.github.com/blueyed/c8470c2aad3381c33ea3