Stephen Fong
Stephen Fong

Reputation: 837

Simulate BASH arrow to get previous command

I'm not asking how to catch the key stroke, based on an internet search I believe this can be done using the Ncurses library https://en.wikipedia.org/wiki/Ncurses

What I want to know is how to display the command in the terminal after I press the key.

Currently I'm trying to replicate part of BASH, what my code does is

stephen@stephen:~/project/simsh$ ./simsh.c
stephen@stephen:~/project/simsh$ pwd
whateverDirectoryI'mNowIn
stephen@stephen:~/project/simsh$

What I want is it can shows the following after I press the Up-Arrow

stephen@stephen:~/project/simsh$ pwd

instead of

stephen@stephen:~/project/simsh$ ^[[A

While I know how to capture the key signal, I don't know how to show the older command out immediately and see it as potential input command.

Upvotes: 1

Views: 242

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

Use the GNU Readline library and it'll handle all of this for you.

GNU Readline is a software library that provides line-editing and history capabilities for interactive programs with a command-line interface, such as Bash. It is currently maintained by Chet Ramey as part of the GNU Project.

It allows users to move the text cursor, search the command history, control a kill ring (a more flexible version of a copy/paste clipboard) and use tab completion on a text terminal. As a cross-platform library, readline allows applications on various systems to exhibit identical line-editing behavior.

Upvotes: 2

Related Questions