Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I accept left/right/up/down arrow inputs in a Linux shell?

I wrote a Java application which has a while(input.readLine()) which continues reading input until the user types a quit command. I have a .bat script to launch it in Windows and a .sh to launch it in Linux. The application works fine in both.

While in Windows, if you type a command like "check email" and hit enter, it will perform the command. Then, at the next prompt (that is: the next time the Java application reads a line of input) you can hit the up arrow and it recalls your "check email" command. You could press the left arrow key to move your cursor left, etc. This is all exactly how I want it.

On Linux, however, pressing the up key causes ^[[D to appear. The left and right arrow keys produce similar ASCII output, like ^[[C.

I've heard of stty and viewed the man pages, but cannot figure out what I need to change in the .sh script with launches my Java application. Can anyone help me?

like image 701
Michael Avatar asked Jan 07 '11 22:01

Michael


1 Answers

The simplest solution is to use an external wrapper that reads a line with edition capabilities, then sends it to your program. A good wrapper is rlwrap.

Using a separate tool is in keeping with the unix philosophy of using separate tools for separate purposes (line edition and whatever your program does). It's also simple: just make your shell wrapper run rlwrap myprogram instead of myprogram.

The underlying readline library (no relation to any readLine method in Java; you'll want a Java wrapper such as Java-Readline) is more work to integrate, and constrains your program to be GPL. Go for that only if you want more than what a wrapper can provide — primarily application-specific completions.

like image 182
Gilles 'SO- stop being evil' Avatar answered Oct 03 '22 06:10

Gilles 'SO- stop being evil'