Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use up arrow key in shell script to get previous command

Tags:

bash

shell

unix

I am trying to write my console with some basic functionalities. Here is what I am doing.

function help()
{
        echo "add(a,b,...)"
}

function add()
{
arg=$(echo $1 | cut -d"(" -f2)
sum=0
for number in `echo ${arg} | sed -e 's/[,) ]\+/\n/g'` ; do
        sum=$(($sum + $number))
done
echo $sum
}

while true
do

echo -n "mycon@avi>>"
read command
opt=$(echo "$command" | cut -d"(" -f1)
case $opt in
"exit"|"q")
        exit
;;
"help")
        help
;;
"add")
        add $command
;;
esac
done

I am saving this file as mycon when I run this script ./mycon

mycon@avi>>add(2,3)
5
mycon@avi>>

Now in this moment when I am pressing up arrow key, I want to get the above add(2,3) command. what is the way to do this ??

Thank You

like image 468
avinashse Avatar asked Feb 11 '23 05:02

avinashse


1 Answers

Bash-only solution:

  1. Change read command to read -e command so that bash will enable the readline library.

  2. Add the command history -s "$command" to include the line read into the history.

Note that read command will delete trailing whitespace from the typed command before assigning the line to command, unless you invoke it with IFS set to the empty string. Also, read will normally treat backslashes as escape characters, which is usually undesirable; you can suppress that behaviour with the -r flag. Finally, you can get read to print the prompt, which will work better with readline, using the -p option. So your final sequence might look like this:

while IFS= read -e -p "mycon@avi>> " command; do
  history -s "$command"
  # ... process the command
done

(Using the read command as the condition in the while statement causes the while loop to terminate if the user enters an EOF character.)

For more information on read and history, use the built-in bash help command (help read / help history)

like image 140
rici Avatar answered Apr 28 '23 06:04

rici