Bash Tricks I Like #2

A terminal needs some colour.

Most terminals these days have support for 256 colours. Here is a bash function that prints the numbers from 0 to 255, each printed in its respective colour. This makes it easy to identify which colours you want to use when you are created or adjusting a colour scheme for your terminal.

colours() {
  local count=0
  local cols=$(tput cols)
  for i in {0..255}; do
    ((count+=4))
    if [ $count -gt $cols ]; then
      printf "\n"
      count=4
    fi
    printf "\x1b[38;5;${i}m%03s " "${i}"
  done
  printf "\n"
}

The heart of the function is the for loop and the following line: printf "\x1b[38;5;${i}m%03s " "${i}". This line is responsible for printing the current number in its respective colour. The rest of the code is for formatting the output nicely in the terminal.