gpt4 book ai didi

bash - 等待 Shell 脚本上的按键

转载 作者:行者123 更新时间:2023-11-29 09:13:38 25 4
gpt4 key购买 nike

我做了一个Bourne shell脚本,我需要通过添加“按Esc按钮执行命令”来改进它。

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

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

但我无法让它在 Bourne shell 中工作 — 错误:“读取:非法选项 -s”

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

最佳答案

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

#!/bin/sh

set -eu

# usage: readc <variable-name>
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 -echo -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
"$(printf '%b' '\033')") echo "escape pressed";;
*) echo "something else" ;;
esac

关于bash - 等待 Shell 脚本上的按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54081579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com