A simple version of your loop might look something like this:
for i in {0..48}; do
echo "$(tput setaf $i)HELLOBASH$(tput sgr0)"
done
If you prefer to use ANSI color codes rather than spawn a subshell to call tput, then you could go this way:
for i in {0..48}; do
echo $'\E[38;5;'$i'm'HELLOBASH$'\E[00m'
done
If you want something more readable, you can use variables:
for i in {0..48}; do
fg=$'\E[38;5;'$i'm'
reset=$'\E[00m'
echo "${fg}HELLOBASH${reset}"
done
Powerlevel10k has a handy one-liner for Zsh users to see a colormap.
I use a modified version of that in Bash and it works great. The only overly clever bit in this snippet is the first 16 colors are special. They take up 8 per line because it looks nicer to line them up that way, and then after that the color sequences need to go in a 6-per line gradient, so there's a bit of modulo/echo magic to make that happen.
function colormap() {
local i bg fg reset
reset=$'\E[00m'
for i in {0..255}; do
fg=$'\E[38;5;'$i'm'
bg=$'\E[48;5;'$i'm'
printf "%s %s" "$bg" "$reset"
printf "%s%03d%s " "$fg" "$i" "$reset"
(( i <= 15 && (i + 1) % 8 == 0 )) && echo
(( i > 15 && (i - 15) % 6 == 0 )) && echo
done
}
The advantage of this is that it's simple, and way faster than making 256 calls to tput
.
tput
command looks up the right codes for colors. – Cupritetput
means you always have the right code for the terminal type you're currently using. – Cuprite