简体   繁体   中英

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

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,

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' ]

ie type these 5 things

$
single quote
Control V
Escape
single quote

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM