2

I'd like to briefly change my terminal output color, run a Ruby script so that standard output prints in that changed color, 'sleep' for a second, and then change it back. I know how to set colors, like for the prompt:

PS1="\e[0;36m[\w] \e[m "

I imagine I need to write a Bash function to do this. What would that look like?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jumar
  • 309
  • 1
  • 2
  • 14

4 Answers4

2

Here is a Ruby script to show all the terminal colors. Download it or run the code below.

def color(index)
  normal = "\e[#{index}m#{index}\e[0m"
  bold = "\e[#{index}m\e[1m#{index}\e[0m"
  "#{normal}  #{bold}  "
end

8.times do|index|
  line = color(index + 1)
  line += color(index + 30)
  line += color(index + 90)
  line += color(index + 40)
  line += color(index + 100)
  puts line
end
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mvndaai
  • 3,453
  • 3
  • 30
  • 34
1

You can do it within Ruby (assuming you're on Linux; Windows requires a library/gem whose name I can't remember at the moment) using the normal codes you would use in bash, e.g.

puts "\e[31m etc Your text here."

To reset to normal display:

puts "\e[0m"

Adjust to taste.

  • This is not bad, but I'd like to do the terminal change without including color-specific printing in each "puts" line. I'm wondering if I can extend 'puts' to always print in a designated color (since I only print with puts anyway). – jumar Apr 12 '13 at 20:39
  • I'd use the Logger class (http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html), and create a class that extends it, and wraps all the output in the appropriate color. You can then pass your "custom" logger to the script, to Rails, to wherever you want, and then call the appropriate output. You can even set the colors differently for warn/info/debug. – Joe Pym Apr 13 '13 at 03:26
  • You only need to print out the code when you want to change it; that is, you can do `puts` (or `print`) `"\e[31m"` at the beginning of your script, and the terminal text color will stay red (or whatever color you choose) until you print another ANSI color code. – Reinstate Monica -- notmaynard Apr 15 '13 at 14:18
1

You can also use the Term Ansicolor gem to change it from inside a running script.

http://flori.github.io/term-ansicolor/

Joe Pym
  • 1,826
  • 12
  • 23
1

One may also use the Colorize gem.

Installation:

sudo gem install colorize

Usage:

require 'colorize'

puts "I am now red.".red
puts "I am now blue.".green
puts "I am a super coder".yellow

This answer is copied from How can I use Ruby to colorize the text output to a terminal?.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
reducing activity
  • 1,985
  • 2
  • 36
  • 64