Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 等待Shell脚本上的按键_Bash_Shell_Unix_Keypress - Fatal编程技术网

Bash 等待Shell脚本上的按键

Bash 等待Shell脚本上的按键,bash,shell,unix,keypress,Bash,Shell,Unix,Keypress,我制作了一个BourneShell脚本,我需要通过添加一个“按Esc按钮执行命令”来改进它 这是BASH中的一个工作示例: #!/bin/bash read -s -n1 key case $key in $'\e') echo "escape pressed";; *) echo "something else" ;; esac 但我无法在Bourne shell中使用它-错误:“读取:非法选项-s” 你能帮我找到一个Bourne shell解决方案吗,因为谷歌上几乎所有的信息都是关于Bas

我制作了一个BourneShell脚本,我需要通过添加一个“按Esc按钮执行命令”来改进它

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

#!/bin/bash
read -s -n1 key
case $key in
$'\e') echo "escape pressed";;
*) echo "something else" ;;
esac
但我无法在Bourne shell中使用它-错误:“读取:非法选项-s”


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

根据我们在评论中的交流,你的具体问题,以及关于Unix和Linux堆栈交换的问题,这是一个完整的解决方案:

#!/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 "$1="
  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 "$1=\${$1}"'$c
        [ "$(($(printf %s "${'"$1"'}" | 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
#/bin/bash
#用法:readc
函数readc()
{
如果[-t0];则
#如果stdin是tty设备,将其从icanon中取出,设置最小值和
#恢复正常值的时间,但不要触摸其他输入或
#或本地设置(回声、isig、icrnl…)。备份
#之前的设置。
已保存的设置=$(stty-g)
stty-icanon最小1次0
fi
评估“$1=”
虽然
#读取一个字节,使用解决该命令的方法
#替换带尾随换行符。
c=$(dd bs=1 count=12>/dev/null;echo。)
c=${c%.}
#在空输入(eof)或满字符时中断循环
#已累积在输出变量中(使用“wc-m”进行计数
#字符数)。
[-n“$c”]&&
评估“$1=\${$1}”$c
[“$($(printf%s“${''$1'}”| wc-m))”-eq 0];do
持续
完成
如果[-t0];则
#如果stdin是tty设备,则还原先前保存的设置。
stty“$已保存的设置”
fi
}
#读一个字符。
readc“键”
#根据已按下的按钮进行操作。
案例$key in
$'\e')回显“按escape”;;
*)呼应“其他东西”;;
以撒

有关使用POSIX sh执行此操作的信息,请参阅(使用
stty
dd
):。