bash 读取命令:以颜色显示提示(或启用反斜杠转义的解释)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24998434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:58:37  来源:igfitidea点击:

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

bashunixterminal

提问by 4wk_

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

我经常使用诸如read -e -p "> All good ? (y/n)" -n 1 confirm;向用户询问确认之类的方法。

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

我正在寻找一种方法来为输出着色,就像命令echo -e一样:

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

I'm using xterm.

我正在使用 xterm。

In man echo, it says :

man echo,它说:

-e enable interpretation of backslash escapes

-e 启用反斜杠转义的解释

Is there a way to do the same thing with the readcommand ? (nothing in the man page :( -roption doesn't work)

有没有办法用read命令做同样的事情?(手册页中没有任何内容:(-r选项不起作用)

回答by chepner

readwon'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,因此您需要按字面意思指定它们。bash的 ANSI 引用字符串对此很有用:

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

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

您还应该能够使用Control-键入文字转义字符vEscape,它将^[在终端中显示:

read -p '^[[31mFoobar^[[0m: ' foo

回答by Vrakfall

I have another solution that allows you to use variables to change the text's format. I echo -ethe the output I want into the -pargument of the readcommand.

我有另一个解决方案,它允许您使用变量来更改文本的格式。我echo -e将我想要的输出输入到命令的-p参数中read

Here's an example:

下面是一个例子:

RESET="3[0m"
BOLD="3[1m"
YELLOW="3[38;5;11m"
read -p "$(echo -e $BOLD$YELLOW"foo bar "$RESET)" INPUT_VARIABLE

回答by Beggarman

Break your query into two components:

将您的查询分为两个部分:

  1. use echo -e -n to display the prompt
  2. collect the user response with read
  1. 使用 echo -e -n 显示提示
  2. 使用 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 -noption suppresses the trailing newline.

echo -n选项抑制尾随换行符。

回答by LuciferHyman

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

mysqlis