Skip to content

Comment on ANSI Escape Codes

Comments

The 256 color palette was the most useful bit for me: not every terminal supports true color, and many terminals allow users to select color themes for the first 16 colors (e.g. "xterm -reverse"). So the upper 240 of the 256 color palette were the most reliable colors.

Here is a shell script to set and use colors. I added the truecolor functions just now.

    #!/bin/dash

    fg () ( printf '\033[38;2;%d;%d;%dm' "${1:-0}" "${2:-0}" "${3:-0}"; )
    bg () ( printf '\033[48;2;%d;%d;%dm' "${1:-0}" "${2:-0}" "${3:-0}"; )
    fg256 () ( printf '\033[38;5;%dm' "${1:-0}"; )
    bg256 () ( printf '\033[48;5;%dm' "${1:-0}"; )


    N='\033[' x=30

    for a in Bl R G Y B M C W  # Black Red Green Yellow Blue Magenta Cyan White
    do eval $a='$N'"'"$((   x))"m'" \
           b$a='$N'"'"$((60+x))"m'" \
        ${a}bg='$N'"'"$((10+x))"m'" \
       b${a}bg='$N'"'"$((70+x))"m'"   # bX=bright Xbg=background bXbg=brgt bgnd
             x=$((1+x)) 
    done

    N=$N'0m'

    printf "${B}${Gbg}This is blue on a green background.$N\n"

    fg 255
    bg 255 255 255

    printf "This is red on a white background.$N\n"

    x=0

    while [ $x -lt 256 ]
    do y=$((255-x))
       fg256 $x
       bg256 $y
       printf "%.3d $N" $x
       [ $(((1+x)%16)) -eq 0 ] && echo ''
       x=$((1+x))
    done

    echo ''
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.