Stephan K.
Stephan K.

Reputation: 15732

Bash script Arrow Keys produces weird characters

Consider the following minimised Bash Script:

echo Enter your name:
read NAME
echo $NAME

Now if I run the script and enter a name and want to navigate through my input with my arrow keys, [[D^ characters are getting returned.

How would you rewrite that script to cater for such behaviour, i.e. let me navigate with keys instead of winning an ASCII contest ?

Upvotes: 4

Views: 2775

Answers (2)

Stephan K.
Stephan K.

Reputation: 15732

Thanks to Andreas and some due dilligence with a search engine, I was able to rewrite my script:

echo Enter your name:
read -e NAME
echo $NAME

Now navigating through the input with arrow keys, works like a expected.

Here you can learn more about the read builtin command.

Upvotes: 1

Andreas Bombe
Andreas Bombe

Reputation: 2470

These character sequences are the way that the terminal communicates that "cursor left" has been pressed. If the program receiving it does not interpret it as such and instead just displays them (after filtering the escape character), that's what you get.

Luckily for you, the read command of bash has the option -e to enable use of Readline for reading in the line. Readline performs all that handling (as it does on the normal bash command input).

Upvotes: 4

Related Questions