包含控制字符的字符串文字

String literal containing control characters

我正在创建一种交互式教程,其工作方式如下:

echo "What do you press if you want to move one word backwords in bash?"
read ans
if [ "$ans" == "ESCb" ]; then
  echo RIGHT!
else
  echo WRONG!
fi

现在,如何在字符串文字中输入 ESC 字符(ASCII 27 十进制)? ESC肯定不行

我知道我最好使用另一种语言,但这是一项作业,需要在 bash 脚本中。

在 bash 中,您可以使用 $'...' 引号:

echo $'\eb' | xxd

比较输入Alt+b输入

read x
echo "$x" | xxd

你有几种方法:

  1. 使用bash的ANSI C expansions:

    if [ "$ans" == $'\eb' ];
    
  2. 在大多数 Unix 终端上,您可以按 CtrlV 进入逐字模式,逐字输入下一个字符。所以,按CtrlV,然后按Esc,那么你应该输入了文字Esc字符。根据您的编辑器,它可能显示为 ^[.
  3. 使用printf, which can interpret various character sequences:

    $ printf '%b' '\e' | od -c
    0000000 033
    0000001
    $ printf '%b' '3' | od -c
    0000000 033
    0000001
    $ printf '%b' '\x1B' | od -c
    0000000 033
    0000001