等待 Shell 脚本上的按键

Wait for a Key press on a Shell Script

我做了一个谍影重重shell脚本,我需要通过添加"Press Esc button to execute a command".

来改进它

这是 BASH 中的一个工作示例:

#!/bin/bash
read -s -n1 key
case $key in
$'\e') echo "escape pressed";;
*) echo "something else" ;;
esac

但我无法在 Bourne 中使用它 shell — 错误:"read: Illegal option -s"

你能帮我找到一个 Bourne shell 解决方案吗,因为 Google 上的几乎所有信息都是关于 Bash 语句的。

根据我们在评论中的交流、您的具体问题以及关于 Unix 和 Linux Stack Exchange Can I read a single character from stdin in POSIX shell? 的问题,这是一个完整的解决方案:

#!/bin/bash

# usage: readc <variable-name>
function readc()
{
  if [ -t 0 ]; then
    # if stdin is a tty device, put it out of icanon, set min and
    # time to sane value, but don't otherwise touch other input or
    # or local settings (echo, isig, icrnl...). Take a backup of the
    # previous settings beforehand.
    saved_tty_settings=$(stty -g)
    stty -icanon min 1 time 0
  fi
  eval "="
  while
    # read one byte, using a work around for the fact that command
    # substitution strips trailing newline characters.
    c=$(dd bs=1 count=1 2> /dev/null; echo .)
    c=${c%.}

    # break out of the loop on empty input (eof) or if a full character
    # has been accumulated in the output variable (using "wc -m" to count
    # the number of characters).
    [ -n "$c" ] &&
      eval "=${}"'$c
        [ "$(($(printf %s "${'""'}" | wc -m)))" -eq 0 ]'; do
    continue
  done
  if [ -t 0 ]; then
    # restore settings saved earlier if stdin is a tty device.
    stty "$saved_tty_settings"
  fi
}

# Reads one character.
readc "key"

# Acts according to what has been pressed.
case $key in
  $'\e') echo "escape pressed";;
  *) echo "something else" ;;
esac