EN
Bash - detect key pressed
9 points
In this short article, we want to show how to handle pressed key without waiting to rerun key / enter key confirmation under Bash.
Quick solution:
xxxxxxxxxx
1
read -r -s -n 1 input
2
3
echo "$input"
Where:
-r
disables waiting to type new line character to end read command (Return / Enter key is not required),-s
does not display typed characters,-n 1
expects to type one character.
Alternatively you can use short version too: read -rsn1 input
In this section, we want to show how to create a simple menu that doesn't require to pres Return / Enter key after the option is typed.
example menu.sh
file:
xxxxxxxxxx
1
2
3
echo '1. Message'
4
echo '2. User'
5
echo '3. Exit'
6
echo
7
echo 'Select one option [1-3]'
8
echo
9
10
while true;
11
do
12
read -r -s -n 1 input
13
14
case "$input" in
15
"1")
16
echo "Selected 1 [1. Message]"
17
;;
18
"2")
19
echo "Selected 2 [2. User]"
20
;;
21
"3")
22
echo "Selected 3 [3. Exit]"
23
exit 0
24
;;
25
esac
26
done
27