Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal containing control characters

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.

like image 525
Boyang Avatar asked May 06 '26 09:05

Boyang


1 Answers

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
    
like image 56
muru Avatar answered May 09 '26 00:05

muru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!