I have a simple while loop accepting input:

while true; do
    read -rep $'\n '"$USER"'> ' userInput
    echo "$userInput"



 username> command1

 username> command2

Is it possible to have a command history? So that I can press up on my keyboard to view the previously executed commands (without leaving the while loop)?

2 Answers 2


You could use the small Readline wrapper rlwrap. This is a neat little tool that provides command history to utilities that don't implement it by themselves.

You would use rlwrap on the script itself:

rlwrap -a ./script.sh

This would save a history file called ~/.script.sh_history and would use that file not only in the current session, but also in future sessions to provide a sort of history that you could step through.

See the manual for rlwrap.

rlwrap is commonly available as a package on most Unices, but may also be had from its GitHub repository.

  • Thanks for your answer. So this isn't possible purely with bash?
    – user321630
    Nov 18, 2018 at 21:31
  • @user321630 The read builtin does not provide this facility. You would have to implement it by saving the inputted data to a file and then somehow search that appropriately when the user uses the arrow keys.
    – Kusalananda
    Nov 18, 2018 at 21:34
  • @Kusalananda I was thinking the same but is there any way to pass up-key as an argument? I searched a lot but no help.
    – Prvt_Yadav
    Nov 18, 2018 at 21:36
  • 1
    @Debian_yadav This is non-trivial as the up-arrow key sends a series of characters, and you would have to distinguish these from other input and to do that without requiring the user to press Enter. Here's the solution to the first part of that problem: bashscript to detect right arrow key being pressed
    – Kusalananda
    Nov 18, 2018 at 21:40

You can use history -s to edit the history list, and read -e to make it possible to view the history.

while true; do
    read -rep $'\n '"$USER"'> ' userInput
    history -s "$userInput"
    echo "$userInput"

Note that there are various options about the command history. The behavior may be very different between a script and an interactive shell. For example, the command history is not loaded from or saved to a file automatically in a script, which may or may not be desirable in your situation. But you can fix it by adding more code if not.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .