作为标题,有什么方法可以在期望外壳中使用彩色文本?就像下面的 shell script echo 命令一样。
echo -e "\033[32m Hello World"
I have been suffering the answer to this question for quite some time, and now I think I've finally got an answer.
How it works is to use 033
to send the < ESC> character and then [
to send ANSI escape codes separated by semicolons, however as [
is a special character it also needs to be escaped with a backslash. You can then proceed to send ANSI sequences and delimit with an m
.
Example ANSI break sequences
0 Reset / Normal all attributes off
1 Bold or increased intensity
4 Underline: Single
30 Set text color Black
31 Set text color Red
32 Set text color Green
Full list can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code
Example:
puts "\033\[01;31m" # This will turn text red
puts "~~~This text is red and bold\n"
puts "\033\[0;32m" # This will turn text green
puts "This text is green and bold switched off\n"
However it doesn't seem to work with the -nonewline
option, which is a tad annoying. However the send_user command seems to handle things a lot better and under control a lot better:
send_user "\033\[01;31mRed bold \033\[0;32mGreen again"
You can even combine this with variables to make the output more readable:
set green "\033\[0;32;40m"
set red "\033\[1;31m"
send_user "${red}Red bold ${green}Green again"