Debian Codegraph @

arrow-detect.sh

raw symbols SCIP
1 #!/bin/bash
2 # arrow-detect.sh: Detects the arrow keys, and a few more.
3 # Thank you, Sandro Magi, for showing me how.
4
5 # --------------------------------------------
6 # Character codes generated by the keypresses.
7 arrowup='\[A'
8 arrowdown='\[B'
9 arrowrt='\[C'
10 arrowleft='\[D'
11 insert='\[2'
12 delete='\[3'
13 # --------------------------------------------
14
15 SUCCESS=0
16 OTHER=65
17
18 echo -n "Press a key... "
19 # May need to also press ENTER if a key not listed above pressed.
20 read -n3 key # Read 3 characters.
21
22 echo -n "$key" | grep "$arrowup" #Check if character code detected.
23 if [ "$?" -eq $SUCCESS ]
24 then
25 echo "Up-arrow key pressed."
26 exit $SUCCESS
27 fi
28
29 echo -n "$key" | grep "$arrowdown"
30 if [ "$?" -eq $SUCCESS ]
31 then
32 echo "Down-arrow key pressed."
33 exit $SUCCESS
34 fi
35
36 echo -n "$key" | grep "$arrowrt"
37 if [ "$?" -eq $SUCCESS ]
38 then
39 echo "Right-arrow key pressed."
40 exit $SUCCESS
41 fi
42
43 echo -n "$key" | grep "$arrowleft"
44 if [ "$?" -eq $SUCCESS ]
45 then
46 echo "Left-arrow key pressed."
47 exit $SUCCESS
48 fi
49
50 echo -n "$key" | grep "$insert"
51 if [ "$?" -eq $SUCCESS ]
52 then
53 echo "\"Insert\" key pressed."
54 exit $SUCCESS
55 fi
56
57 echo -n "$key" | grep "$delete"
58 if [ "$?" -eq $SUCCESS ]
59 then
60 echo "\"Delete\" key pressed."
61 exit $SUCCESS
62 fi
63
64
65 echo " Some other key pressed."
66
67 exit $OTHER
68
69 # ========================================= #
70
71 # Mark Alexander came up with a simplified
72 #+ version of the above script (Thank you!).
73 # It eliminates the need for grep.
74
75 #!/bin/bash
76
77 uparrow=$'\x1b[A'
78 downarrow=$'\x1b[B'
79 leftarrow=$'\x1b[D'
80 rightarrow=$'\x1b[C'
81
82 read -s -n3 -p "Hit an arrow key: " x
83
84 case "$x" in
85 $uparrow)
86 echo "You pressed up-arrow"
87 ;;
88 $downarrow)
89 echo "You pressed down-arrow"
90 ;;
91 $leftarrow)
92 echo "You pressed left-arrow"
93 ;;
94 $rightarrow)
95 echo "You pressed right-arrow"
96 ;;
97 esac
98
99 exit $?
100
101 # ========================================= #
102
103 # Antonio Macchi has a simpler alternative.
104
105 #!/bin/bash
106
107 while true
108 do
109 read -sn1 a
110 test "$a" == `echo -en "\e"` || continue
111 read -sn1 a
112 test "$a" == "[" || continue
113 read -sn1 a
114 case "$a" in
115 A) echo "up";;
116 B) echo "down";;
117 C) echo "right";;
118 D) echo "left";;
119 esac
120 done
121
122 # ========================================= #
123
124 # Exercise:
125 # --------
126 # 1) Add detection of the "Home," "End," "PgUp," and "PgDn" keys.