Com*_*mon 5 unix bash shell keypress
我制作了一个Bourne shell脚本,我需要通过添加“按 Esc 按钮执行命令”来改进它。
\n\n这是BASH中的一个工作示例:
\n\n#!/bin/bash\nread -s -n1 key\ncase $key in\n$\'\\e\') echo "escape pressed";;\n*) echo "something else" ;;\nesac\nRun Code Online (Sandbox Code Playgroud)\n\n但我无法使其在 Bourne shell \xe2\x80\x94 中工作 错误:“读取:非法选项 -s”
\n\n你能帮我找到一个 Bourne shell 解决方案吗,因为 Google 上几乎所有的信息都是关于 Bash 语句的。
\n根据我们在评论中的交流、您的具体问题以及 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
Run Code Online (Sandbox Code Playgroud)