我想做一個非常簡單的bash腳本,模擬外觀複選框的行爲! 我希望它顯示一些選項,並根據按下左或右箭頭鍵將光標移動到下一個複選框。我已經設法使用READ和Ansii轉義序列來檢測箭頭鍵,並使用tput來移動光標。複選框與bash腳本
我的問題是這是我需要閱讀某個字母(例如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 wich 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
是的,我知道,這不是最完美的代碼,但我想了解:
我已經這樣做了這麼遠。建議將非常感激。
你看過bash'select'語句了嗎?這不完全是複選框,但它是一個編號菜單。 – SiegeX 2012-01-11 04:43:54
@SiegeX是的,我知道這個命令並嘗試過,但是我沒有找到一種方法來迫使它只接受鍵盤上的某些鍵。我希望我的小腳本能夠保護用戶安全= P我的意思是用戶無法輸入任何內容的方式!使用select即使它很有用,如果選項是1,2,3,用戶可以鍵入idfsbhisdolasokjcmnh,我希望它們被迫只鍵入需要的內容,並將鍵盤的其餘部分「鎖定」。感謝您的回覆;) – Metafaniel 2012-01-11 15:28:53