In the mac terminal - how can I get arrow keystrokes from stdin?

江枫思渺然 提交于 2019-12-25 07:49:40

问题


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 -

  1. a way to simulate key presses to an application, or
  2. a way to generate simple dialog boxes, or
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!