1---
 2title: Display xterm color palette
 3url: xterm-color-palette.html
 4date: 2023-05-25T12:00:00+02:00
 5type: note
 6draft: false
 7---
 8
 9- `bash xterm-palette.sh` - will show you number of max colors available
10- `bash xterm-palette.sh -v` - will create a list of all colors with codes
11
12![xterm color palette](/assets/notes/xterm-palette.png)
13
14```sh
15#!/usr/bin/env bash
16# xterm-palette.sh
17
18trap 'tput sgr0' exit		# Clean up even if user hits ^C
19
20function setfg () {
21    printf '\e[38;5;%dm' $1
22}
23
24function setbg () {
25    printf '\e[48;5;%dm' $1
26}
27
28function showcolors() {
29    # Given an integer, display that many colors
30    for ((i=0; i<$1; i++))
31    do
32	printf '%4d ' $i
33	setbg $i
34	tput el
35	tput sgr0
36	echo
37    done
38    tput sgr0 el
39}
40
41# First, test if terminal supports OSC 4 at all.
42printf '\e]4;%d;?\a' 0
43read -d $'\a' -s -t 0.1 </dev/tty
44if [ -z "$REPLY" ]
45then
46    # OSC 4 not supported, so we'll fall back to terminfo
47    max=$(tput colors)
48else
49    # OSC 4 is supported, so use it for a binary search
50    min=0
51    max=256
52    while [[ $((min+1)) -lt $max ]]
53    do
54	i=$(( (min+max)/2 ))
55	printf '\e]4;%d;?\a' $i
56	read -d $'\a' -s -t 0.1 </dev/tty
57	if [ -z "$REPLY" ]
58	then
59            max=$i
60	else
61	    min=$i
62	fi
63    done
64fi
65
66
67# If -v is given, show all the colors
68case ${1-none} in
69    none)
70	echo $max
71	;;
72    -v)
73	showcolors $max
74	;;
75    *)
76	if [[ "$1" -gt 0 ]]; then
77	    showcolors $1
78	else
79	    echo $max
80	fi
81	;;
82esac | less --raw-control-chars --QUIT-AT-EOF --no-init
83```