读取命令:以颜色显示提示(或启用反斜杠转义的解释) [英] Read Command : Display the prompt in color (or enable interpretation of backslash escapes)
问题描述
我经常使用类似 read -e -p "> All good ? (y/n)" -n 1 confirm;
来向用户请求确认.
I often use something like read -e -p "> All good ? (y/n)" -n 1 confirm;
to ask a confirm to the user.
我正在寻找一种方法来为输出着色,就像命令 echo -e
所做的那样:
I'm looking for a way to colorize the output, as the command echo -e
does :
echo -e " 33[31m";
echo "Foobar"; // will be displayed in red
echo -e " 33[00m";
我正在使用 xterm.
I'm using xterm.
在man echo
中,它说:
-e 启用反斜杠转义解释
-e enable interpretation of backslash escapes
有没有办法用 read
命令做同样的事情?(手册页中没有任何内容 :( -r
选项不起作用)
Is there a way to do the same thing with the read
command ? (nothing in the man page :( -r
option doesn't work)
推荐答案
read
不会处理 -p
参数中的任何特殊转义,因此您需要从字面上指定它们.bash
的 ANSI 引用字符串对此很有用:
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[31mFoobare[0m: ' foo
您还应该能够使用 Control-v Escape 键入文字转义字符,它将显示为 ^[
在终端:
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
这篇关于读取命令:以颜色显示提示(或启用反斜杠转义的解释)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!