One day, I typed the command
echo "\033[32mHELLOBASE\033[m"
in the gnome bash shell. The terminal showed me a green HELLOBASH string. I found this interesting. From my experience and serveral tests, I can change the number 32 from 0 up to 47. Next I wrote the following code,
for i in {0..48};do
echo \033[$imHELLOBASH\[033m
done
Of course, it doesn't work, or I cannot be here! So how to improve the above code to function?
Let's do this the right way -- looking up color codes in our termcap
(or, for modern systems, terminfo
) database using the tput
command:
for ((i=0; i<=48; i++)); do
tput setaf "$i"
echo HELLOBASH
done
If you want to see all available colors on a 256-color terminal, use this code token from BashFAQ #37:
colors256() {
local c i j
printf "Standard 16 colors\n"
for ((c = 0; c < 17; c++)); do
printf "|%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n\n"
printf "Colors 16 to 231 for 256 colors\n"
for ((c = 16, i = j = 0; c < 232; c++, i++)); do
printf "|"
((i > 5 && (i = 0, ++j))) && printf " |"
((j > 5 && (j = 0, 1))) && printf "\b \n|"
printf "%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n\n"
printf "Greyscale 232 to 255 for 256 colors\n"
for ((; c < 256; c++)); do
printf "|%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n"
}
colors256
For additional background on how and why any of this works, see the bash-hackers page on terminal codes.
As for why your original code didn't work even on terminals using ANSI color codes, by the way -- @rici pegged it correctly: Your parameter expansion was ambiguous without adding curly braces.
That is to say:
$imHELLOBASH
...needed to be...
${i}mHELLOBASH
...to avoid the shell trying to find and expand a variable called imHELLOBASH
rather than a variable named i
.