bash - How to enable the up/down arrow keys to show previous inputs when using `read`? -
i'm waiting user input (using 'read') in infinite loop , have command history, being able show previous inputs entered, using , down arrow keys, instead of getting ^[[a , ^[[b. possible?
thanks @l0b0 answer. got me on right direction. after playing time i've realized need following 2 features, haven't managed them yet:
if press , add previous command have whole thing saved in history, not addition. example
$ ./up_and_down
enter command: hello
enter
enter command:
up
enter command: hello you
enter
enter command:
up
enter command: you
(instead of "hello you")if can't keep going because i'm @ end of history array, don't want cursor move previous line, instead want stay fixed.
this have far (up_and_down):
#!/usr/bin/env bash set -o nounset -o errexit -o pipefail read_history() { local char local string local esc=$'\e' local up=$'\e[a' local down=$'\e[b' local clear_line=$'\r\e[k' local history=() local -i history_index=0 # read 1 character @ time while ifs="" read -p "enter command:" -n1 -s char ; if [[ "$char" == "$esc" ]]; # rest of escape sequence (3 characters total) while read -n2 -s rest ; char+="$rest" break done fi if [[ "$char" == "$up" && $history_index > 0 ]] ; history_index+=-1 echo -ne $clear_line${history[$history_index]} elif [[ "$char" == "$down" && $history_index < $((${#history[@]} - 1)) ]] ; history_index+=1 echo -ne $clear_line${history[$history_index]} elif [[ -z "$char" ]]; # user pressed enter echo history+=( "$string" ) string= history_index=${#history[@]} else echo -n "$char" string+="$char" fi done } read_history
two solutions using -e
option read
command combined builtin history
command:
# version 1 while ifs="" read -r -e -d $'\n' -p 'input> ' line; echo "$line" history -s "$line" done # version 2 while ifs="" read -r -e -d $'\n' -p 'input> ' line; echo "$line" echo "$line" >> ~/.bash_history history -n done
Comments
Post a Comment