3

I'm creating a sort of interactive tutorial that works like the following:

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

Now, how can I input the ESC character (ASCII 27 decimal) in string literal? ESC certainly doesn't work.

I understand I probably better off use another language, but this is an assignment and it's required to be in bash script.

Boyang
  • 2,520
  • 5
  • 31
  • 49

2 Answers2

8

You have a couple of ways:

  1. Use bash's ANSI C expansions:

    if [ "$ans" == $'\eb' ];
    
  2. On most Unix terminals, you can press CtrlV to enter a verbatim mode, where the next character is entered verbatim. So, press CtrlV, then Esc, then you should have entered a literal Esc character. Depending on your editor, it could show up as ^[.
  3. Use printf, which can interpret various character sequences:

    $ printf '%b' '\e' | od -c
    0000000 033
    0000001
    $ printf '%b' '\033' | od -c
    0000000 033
    0000001
    $ printf '%b' '\x1B' | od -c
    0000000 033
    0000001
    
muru
  • 4,723
  • 1
  • 34
  • 78
3

In bash, you can use the $'...' quotes:

echo $'\eb' | xxd

Compare with entering Alt+bEnter to

read x
echo "$x" | xxd
choroba
  • 231,213
  • 25
  • 204
  • 289