读取命令:以彩色显示提示(或启用反斜杠转义的解释) [英] 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 "\033[31m";
echo "Foobar"; // will be displayed in red
echo -e "\033[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[31mFoobar\e[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屋!