3

I want to use user input of special characters in conditional statement. I tried:

read -p "press arrow up" foo
if [ $foo == "^[[A" ]; then echo yes; fi

It did not do what I wanted it to do.

3
  • 1
    You could do: if [ "$foo" = "$(xxd -r <<< "00000000: 1b5b 410a")" ];, but there might be a better option.
    – pLumo
    Jun 29 at 13:45
  • @pLumo Is there a map for all special characters for this format: (xxd -r <<< "00000000: 1b5b 410a"? Jun 29 at 13:48
  • 1
    No, I just made xxd <<< "$foo" and copy-pasted ;-)
    – pLumo
    Jun 29 at 13:48

2 Answers 2

3

In bash, you could use ANSI-C quoting

#!/bin/bash

read -p "press arrow up " foo

if [ "$foo" = $'\e[A' ]; then
  echo 'yes'
fi

For a more nuanced version, see BASH question: using read, can I capture a single char OR arrow key (on keyup)

2

Not especially beautiful, but you could compare hex values.

To find out hex value of up arrow, assign foo manually and run

xxd <<< "$foo"

Copy paste the output to your script and use xxd -r to revert the hex value:

up_arrow="$(xxd -r <<< "00000000: 1b5b 410a")"
if [ "$foo" = "$up_arrow" ]; then echo yes; fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.