puts Ruby.in_colour!

When I’m making a script for someone I always think it’s nice to add a bit of colour to anything output by Ruby. Not to be garish… We don’t want command line filth reminiscent of Geocities after all! But if there’s an obvious exception that ends our fun it’s good to highlight that.

When working with colour in Terminal we have to use a rather cryptic series of escape characters with colour codes to present the user with some beautiful letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env ruby -wdK
 
esc = "\033["
fgs = (30..37).to_a
bgs = (40..47).to_a
box_width = 4 + 4 * bgs.length
 
puts "", "Ruby colour box".center(box_width), ""
 
print " "*4
 
bgs.each_with_index do |bg, i|
  fg = fgs[i]
  print " #{bg} "
end
 
print "\n"
 
fgs.each do |fg|
  print " #{fg} "
  bgs.each do |bg|
    print "#{esc}#{fg};#{bg}m #{fg} #{esc}0m"
  end
  print "\n"
end
 
puts "", "http://www.theonlyjames.com".center(box_width), ""

The Ruby script illustrates the structure pretty well. You have an escape character (in our script it’s defined as “\033″. For convenience I’ve bundled the “[” on the end of my variable) followed by the foreground colour code, a semicolon, the background colour code and finally a closing “m.”

The escape character and the following options are cumulatively called an escape sequence.

After our string we restore the default colours using another escape character followed by “0m.”

There are a number of further codes we can use after our escape sequence to control the behaviour of our shell although most are fairly specific to the environment in which you run them.

Worth noting, something I played with after starting to use colour. I drafted a quick colour check step that could be added to any script before we start printing out illegible escape sequences that might not be interpreted. For example, when testing quickly in TextMate

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env ruby -wdK
 
term = %x(echo $TERM).strip!
 
print "\n"
 
if term.downcase == "xterm-color"
  puts "Colour supported in \033[32;40m#{term}\033[0m!"
else
  puts "Unknown environment (#{term})."
end
 
print "\n"

Leave a Reply