我正在尝试做一个非常简单的 bash 脚本,它在外观上模拟复选框的行为!
我希望它显示一些选项并根据向左或向右箭头键的按键将光标移动到下一个复选框。我已经设法使用 READ 和 Ansii 转义序列来检测箭头键并使用 tput 来移动光标。
我的问题是我需要阅读要按下的某个字母(例如 x),然后采取另一个行动。但是我怎样才能检测到这个按键,同时检测它是否被按下了箭头键呢?
要检测 ansii 代码,我需要读取 3 个字符,并且使用 X 字符(“选择”的键)我只需要读取一个字符,我怎样才能读取 3 个字符并同时读取一个字符?
此外,我一直在尝试做一些事情,这样用户就可以按向左或向右箭头键或 x 键,但如果他按任何其他键,什么都不会发生!
我已经做到了这一点:
#!/bin/bash
## Here I just print in the screen the "form" with the "checkboxes"
function screen_info(){
clear
cat <<EOF
/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_
||
|| 1[ ] 2[ ] 3[ ]
||
#############################
EOF
}
## This function detects the arrow keys and moves the cursor
function arrows(){
## I use ANSII escape sequences to detect the arrow keys
left_arrow=$'\x1b\x5b\x44' #leftuierda
right_arrow=$'\x1b\x5b\x43' #rightecha
just_x_key=""
## With tput I move the cursor accordingly
cursor_x=14
cursor_y=3
tput cup $cursor_y $cursor_x
while [ -z "$just_x_key" -o "$just_x_key" != "$just_x_key" ]; do
read -s -n3 key
while [ `expr length "$key"` -ne 3 ]; do
key=""
read -s -n3 key
break
done
case "$key" in
$left_arrow)
if [ $cursor_x -gt 14 ]; then
cursor_x=`expr $cursor_x - 8`
fi
tput cup $cursor_y $cursor_x
#This is supposed to be a simple condition detecting the x key pressed which I want to trigger something... But how to read a single character to this condition and 3 characters at the same time if the user presses the arrow key ???? =/
#read -s just_x_key
#if [ $just_x_key == x ]; then
# echo X
# tput cup 7 15
# echo "YOU PRESSED THE RIGHT KEY!!! =D"
#fi
;;
$right_arrow)
if [ $cursor_x -lt 28 ]; then
cursor_x=`expr $cursor_x + 8`
fi
tput cup $cursor_y $cursor_x
#read -s just_x_key
#if [ $just_x_key == x ]; then
# echo X
# tput cup 7 15
# echo "YOU PRESSED THE RIGHT KEY!!! =D"
#fi
;;
esac
done
exit $?
}
#EXECUTION
#=========
## I just call the functions!
screen_info
arrows
是的,我知道,这不是最完美的代码,但我正在努力学习。建议将不胜感激。