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.
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.
Sign up to join this communityI 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.
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)
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
if [ "$foo" = "$(xxd -r <<< "00000000: 1b5b 410a")" ];
, but there might be a better option.xxd <<< "$foo"
and copy-pasted ;-)