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?

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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).
I'd use the Logger class (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.
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.
1

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

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

Comments

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?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.