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

后端 未结 4 2019
星月不相逢
星月不相逢 2020-12-09 02:33

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 outpu

相关标签:
4条回答
  • 2020-12-09 02:51

    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:

    more example ,see the show case ,link is :

    mysqlis

    0 讨论(0)
  • 2020-12-09 02:55

    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.

    0 讨论(0)
  • 2020-12-09 03:15

    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
    
    0 讨论(0)
  • 2020-12-09 03:16

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

    Here's an example:

    RESET="\033[0m"
    BOLD="\033[1m"
    YELLOW="\033[38;5;11m"
    read -p "$(echo -e $BOLD$YELLOW"foo bar "$RESET)" INPUT_VARIABLE
    
    0 讨论(0)
提交回复
热议问题