Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
运行Ruby脚本时更改Bash终端输出颜色_Ruby_Bash - Fatal编程技术网

运行Ruby脚本时更改Bash终端输出颜色

运行Ruby脚本时更改Bash终端输出颜色,ruby,bash,Ruby,Bash,我想简单地更改一下终端输出的颜色,运行一个Ruby脚本,让标准输出以更改后的颜色“sleep”打印一秒钟,然后再更改回来。我知道如何设置颜色,例如提示: PS1="\e[0;36m[\w] \e[m " 我想我需要编写一个Bash函数来实现这一点。那会是什么样子?您可以在Ruby中使用您在bash中使用的普通代码来实现这一点(假设您在Linux上;Windows需要一个库/gem,我现在记不起它的名称),例如 puts "\e[31m etc Your text here.

我想简单地更改一下终端输出的颜色,运行一个Ruby脚本,让标准输出以更改后的颜色“sleep”打印一秒钟,然后再更改回来。我知道如何设置颜色,例如提示:

PS1="\e[0;36m[\w] \e[m "
我想我需要编写一个Bash函数来实现这一点。那会是什么样子?

您可以在Ruby中使用您在bash中使用的普通代码来实现这一点(假设您在Linux上;Windows需要一个库/gem,我现在记不起它的名称),例如

puts "\e[31m etc Your text here."
要重置为正常显示,请执行以下操作:

puts "\e[0m"

根据口味进行调整。

您还可以使用术语Ansicolor gem在运行脚本中对其进行更改


这是一个Ruby脚本,用于显示所有终端颜色。或者运行下面的代码

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
您也可以使用

安装:

sudo gem install colorize
用法:

require 'colorize'

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

这个答案是从中复制的。

这还不错,但我希望在每个“puts”行中不包含特定颜色的打印,而进行终端更改。我想知道是否可以扩展“put”以始终以指定的颜色打印(因为我只打印put)。我将使用Logger类(),创建一个扩展它的类,并将所有输出包装为适当的颜色。然后,您可以将“自定义”记录器传递到脚本、Rails和任何您想要的地方,然后调用适当的输出。您甚至可以为warn/info/debug设置不同的颜色;也就是说,您可以在脚本开始时执行
put
(或
print
“\e[31m”
,并且终端文本颜色将保持红色(或您选择的任何颜色),直到您打印另一个ANSI颜色代码。