read command is specific,
a = this is one character
up arrow = these are three characters
I tried to change a script which is based on another script from the internet
Code: Select all
#!/bin/bash
# https://unix.stackexchange.com/questions/179191/bashscript-to-detect-right-arrow-key-being-pressed
# https://dirask.com/posts/Bash-detect-arrow-key-pressed-jvRlVj
# man read
# https://ss64.com/bash/read.html
GetPos() {
IFS=';' read -sdR -p $'\E[6n' ROW COL
Col=$(( ${COL#*[} -1 ))
Row=$(( ${ROW#*[} -1 ))
}
# Will print position
Func_Up() { GetPos ; echo -n $Col ;}
Func_Down() { GetPos ; echo -n $Row ;}
# Will move cursor
Func_Right() { GetPos ; tput cup "$Row" "$(( $Col + 1 ))" ;}
Func_Left() { GetPos ;
if [[ "Col" -gt 0 ]] ; then
tput cup "$Row" "$(( $Col - 1 ))"
fi ;}
Func_Backspace() {
GetPos
# It may not be possible to read the content from the screen
# But you can,
# 1. Store each letter you typed into a variable,
# 2. Edit a variable
# 3. Move cursor to the beginning
# 4. Clear the screen
# 5. Print the variable again
# Here I delete everything to the right of the cursor
Func_Left ; tput ed
}
#while read -rsn1 ui; do
while read -rsN1 ui; do
case "$ui" in
$'\x1b') # Handle ESC sequence.
# Flush read. We account for sequences for Fx keys as
# well. 6 should suffice far more then enough.
read -rsn1 -t 0.1 tmp
if [[ "$tmp" == "[" ]]; then
read -rsn1 -t 0.1 tmp
case "$tmp" in
"A") Func_Up ;;
"B") Func_Down ;;
"C") Func_Right ;;
"D") Func_Left ;;
esac
else
echo "$tmp"
fi
# Flush "stdin" with 0.1 sec timeout.
# Creates extra letters when keys are pressed for a long time
# read -rsn5 -t 0.1
;;
# Other one byte (char) cases. Here only quit.
# showkey -a
q) echo q ; break ;;
# "") echo "Enter" ;; # the same for spacebar when is "read -n" instead "read -N"
# $'\15') echo "Enter" ;; # Not working
# https://stackoverflow.com/questions/2612274/bash-shell-scripting-detect-the-enter-key
# https://stackoverflow.com/questions/3871729/transmitting-newline-character-n
# $'\x0a') echo "Enter" ;; # I don't know from where is x0a , probably unicode
$'\12') echo "Enter" ;;
$'\40') echo "Space Bar" ;;
$'\177') Func_Backspace ;;
*) echo -n "$ui" ;;
esac
done
when I hold down the "right arrow" and "left arrow" keys
I see sometimes
Code: Select all
^[[C ^[[D ^[[C