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
Read Command : Display the prompt in color (or enable interpretation of backslash escapes)
提问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 -e
does :
我正在寻找一种方法来为输出着色,就像命令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 read
command ? (nothing in the man page :( -r
option doesn't work)
有没有办法用read
命令做同样的事情?(手册页中没有任何内容:(-r
选项不起作用)
回答by chepner
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
,因此您需要按字面意思指定它们。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 -e
the the output I want into the -p
argument of the read
command.
我有另一个解决方案,它允许您使用变量来更改文本的格式。我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:
将您的查询分为两个部分:
- use echo -e -n to display the prompt
- collect the user response with read
- 使用 echo -e -n 显示提示
- 使用 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选项抑制尾随换行符。