Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

color texts at expect shell

As the title, is there any way to use color texts at expect shell? Like the shell script echo command below.

echo -e "\033[32m Hello World"
like image 815
jaeyong Avatar asked Oct 14 '12 05:10

jaeyong


People also ask

How do you color text in terminal?

A script can use escape sequences to produce colored text on the terminal. Colors for text are represented by color codes, including, reset = 0, black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, and white = 37.

How do you color text in bash?

The escape sequence for specifying color codes is \e[COLORm (COLOR represents our color code in this case). By default, echo does not support escape sequences. We need to add the -e option to enable their interpretation. The \e[0m means we use the special code 0 to reset text color back to normal.

How do I change the color of my bash output?

For example, if you wanted to print green text, you could do the following: #!/bin/bash # Set the color variable green='\033[0;32m' # Clear the color after that clear='\033[0m' printf "The script was executed ${green}successfully${clear}!"


1 Answers

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"
like image 110
fileinsert Avatar answered Sep 23 '22 07:09

fileinsert