Put some colour in your life!


This one-liner is a pretty harmless and easy one, yet very very useful (as you might be seeing in one of my next entries).

for i ({000..255}){[ $((i%20)) = 0 ] && printf "\n";printf "\x1b[38;5;${i}m${i} "}

This will actually just work in the Z-Shell, there’s a slightly longer version you’d have to use if you don’t use the Z-Shel (you masochist! 😉 ).

i=0;while [ $i -le 255 ];do [ $((i%20)) = 0 ] && printf "\n";printf "\x1b[38;5;${i}m${i} ";i=$(($i+1));done

What does it do? Well I’ll show you a more comfortable version of it:

i=0;
while [ $i -le 255 ]
do
    if [ $((i%20)) = 0 ]
    then
        printf "\n"
    fi
    printf "\x1b[38;5;${i}m${i} "
    i=$(($i+1));
done

If you ever worked with colors in the shell, you might right away see it: It’s the CSI codes for colors defined by the ANSI escape sequences. So the script goes through all possible 255 color codes that are available on your systems shell and prints the corresponding number in its color. By making use of every shells lazy evaluation the if <cond>; then; <expr>; fi becomes the neat and compact <cond> && <expr>. Making use of Z-Shells highly sophisticated brace expansion our i=0; while <$i-cond>; do; <expr>; <$i-expr>; done becomes for i in <brace>; do <expr>; done. The brace expression is then evaluated to a list from 000, 001,… to 099 and then further on to 255, so it is as if all those numbers were actually written out as list (which is why we can use for in this case). Using the short form of for-loops in zsh it then becomes for i (<brace>){<expr>}. Neat and sweet, wouldn’t you say?

Now you could even make it more compact, if you don’t care about how it is broken into lines (that’s why there’s the modulo part printing an printf “\n” after each 20 numbers (thus with space 4 chars * 20 = 80 chars per line), you could remove it and end up with printing one huge line, or even one huge column:

for i ({000..255}){ printf "\x1b[38;5;${i}m${i}\n"}

Why bother? Well let me lose some short thoughts on that:

Continue reading

Advertisements