Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Command : Display the prompt in color (or enable interpretation of backslash escapes)

I often use something like read -e -p "> All good ? (y/n)" -n 1 confirm; to ask a confirm to the user.

I'm looking for a way to colorize the output, as the command echo -e does :

echo -e "\033[31m";
echo "Foobar";       // will be displayed in red
echo -e "\033[00m";

I'm using xterm.

In man echo, it says :

-e enable interpretation of backslash escapes

Is there a way to do the same thing with the read command ? (nothing in the man page :( -r option doesn't work)

like image 581
4wk_ Avatar asked Jul 28 '14 15:07

4wk_


4 Answers

read won't process any special escapes in the argument to -p, so you need to specify them literally. bash's ANSI-quoted strings are useful for this:

read -p $'\e[31mFoobar\e[0m: ' foo

You should also be able to type a literal escape character with Control-v Escape, which will show up as ^[ in the terminal:

read -p '^[[31mFoobar^[[0m: ' foo
like image 52
chepner Avatar answered Oct 22 '22 00:10

chepner


Here's another solution that allows to use variables to change the text's format. echo -e the wanted output into the -p argument of the read command.

Example:

RESET="\033[0m"
BOLD="\033[1m"
YELLOW="\033[38;5;11m"
read -p "$(echo -e $BOLD$YELLOW"foo bar "$RESET)" INPUT_VARIABLE
like image 40
Vrakfall Avatar answered Oct 22 '22 01:10

Vrakfall


Break your query into two components:

  1. use echo -e -n to display the prompt
  2. collect the user response with read

e.g:

echo -e -n "\e[0;31mAll good (y/n)? "   # Display prompt in red
echo -e -n '\e[0;0m'                    # Turn off coloured output
read                                    # Collect the user input

The echo -n option suppresses the trailing newline.

like image 22
Beggarman Avatar answered Oct 21 '22 23:10

Beggarman


this work for me :

    BC=$'\e[4m'
    EC=$'\e[0m'

    while true; do
            read -p "Do you wish to copy table from ${BC}$HOST $PORT${EC} to ${BC}$LOCAL_HOST $LOCAL_PORT${EC}? (y or n)" yn
        case $yn in
        ....
    done

Results are as follows: enter image description here

more example ,see the show case ,link is :

mysqlis

like image 8
LuciferJack Avatar answered Oct 22 '22 00:10

LuciferJack