jumar
jumar

Reputation: 309

Change Bash terminal output color while running a Ruby script

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?

Upvotes: 2

Views: 2001

Answers (4)

reducing activity
reducing activity

Reputation: 2264

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

Upvotes: 1

mvndaai
mvndaai

Reputation: 3831

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

Upvotes: 2

Joe Pym
Joe Pym

Reputation: 1836

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

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

Upvotes: 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.

Upvotes: 1

Related Questions