我制作了一个 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语句的。
答案 0 :(得分:3)
根据我们在评论中的交流,您的特定问题以及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 "$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