问题
I'd like to browse a terminal dialog menu with the arrow keys (like bash 'dialog')
I would prefer ruby solution, but bash/python could work.
read -n1 input # is not good enough, cause the arrow keys are not regular chars.
Also, the 'read' in mac term doesn't support smaller timeout than 1 second.
Anything?
Thanks,
回答1:
I am not sure what you are looking for -
- a way to simulate key presses to an application, or
- a way to generate simple dialog boxes, or
- a way to read characters from a keyboard...
However, these may give you some ideas:
For 1: You would probably need to look at the Automator and Applescript
tell application "System Events" to tell process "Finder"
click menu item "New Finder Window" of menu 1 of menu bar item "File" of menu bar 1
end tell
For 2: You could look at Platypus for generating dialog boxes and wrappers around scripts - available here
For 3: The following may do something like you want
#!/bin/bash
#
# Read a key in cbreak mode
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
#
# If ESCAPE, read next part
if [ $KEY = $'' ]; then
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
[ $KEY = "A" ] && echo UP
[ $KEY = 'B' ] && echo DOWN
[ $KEY = 'C' ] && echo RIGHT
[ $KEY = 'D' ] && echo LEFT
exit
fi
echo $KEY
I should explain that the if [ $KEY
line needs to be typed
if [ $KEY = $'CONTROL-V ESCAPE' ]
i.e. type these 5 things
$
single quote
Control V
Escape
single quote
回答2:
According to Mark Setchell, minor modification:
#!/bin/bash
# Read a key in cbreak mode
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
# Check if it's a single alphanumeric char
if $(echo $KEY | grep -q -e "[a-zA-Z0-9]"); then
echo $KEY
exit
# Else we assume escape char (doesn't cover all cases)
else
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
[ $KEY == 'A' ] && echo UP
[ $KEY == 'B' ] && echo DOWN
[ $KEY == 'C' ] && echo RIGHT
[ $KEY == 'D' ] && echo LEFT
exit
fi
来源:https://stackoverflow.com/questions/24648228/in-the-mac-terminal-how-can-i-get-arrow-keystrokes-from-stdin