如何使用read -p命令启用“ \ n”解释?

问题描述

提示后,以下代码不显示换行符:

function renderOrNot {
read -n 1 -p "Press 'q' to exit or any other key to repeat rendering.\n" response

if [[ $response == "q" ]] ; then
  exit
else
  nice -19 prependRpollen.py && nice -19 template.sh && nice -19 raco pollen render *.html.P*
  renderOrNot
fi   }

nice -19 prependRpollen.py && nice -19 template.sh && nice -19 raco pollen render *.html.P*
renderOrNot

为了启用反斜杠解释,我不得不诉诸使用 echo -e 显示我的提示,就像这样:

function renderOrNot {
echo -e "Press 'q' to exit or any other key to repeat rendering.\n" 
read -n 1 response

是否可以在 read -p 命令中完成反斜杠解释?

解决方法

read -p "prompt"不能解释提示字符串中的转义符。

尽管字符串文字使用$'I am an ANSI-C style string\nin a shell script\n'

的POSIX候选ANSI-C样式字符串语法,但可以转义表示控制字符。

这种类型的字符串可用于Bash read -p提示字符串,如下所示:

read -n 1 -p $'Press \'q\' to exit or any other key to repeat rendering.\n' response

对于ANSI-C样式的字符串,您也可以将换行符直接添加到字符串中,如下所示:

read -n 1 -p "Press 'q' to exit or any other key to repeat rendering.
" response

还请注意,read -p提示和read -n <integer>个要读取的字符是Bash特定的功能,以及echo -e使echo解释字符串文字的转义