我想保存,然后在使用stdin
的脚本中恢复当前的D1
设置,但是stty -g
正在抱怨:
标准输入:设备不合适的ioctl
我已经尝试关闭stdin
文件描述符,并使用重写的FDs在子subshell中调用stty
。我不知道如何将stdin
和stty -g
分开,我希望得到帮助或建议。
注意,我对POSIX兼容性特别感兴趣。请勿使用Bash/Zsh语言。
重现问题的最小脚本:
#!/usr/bin/env sh
# Save this so we can restore it later:
saved_tty_settings=$(stty -g)
printf 'stty settings: "%s"\n' "$saved_tty_settings"
# ...Script contents here that do something with stdin.
# Restore settings later
# (not working because the variable above is empty):
stty "$saved_tty_settings"
与print 'foo\nbar\n' | ./sttytest
一起运行以查看错误。
发布于 2019-09-21 09:14:51
@icarus的评论:
也许是
saved_tty_settings=$(stty -g < /dev/tty)
?
其实是指向正确的方向,但这不是故事的结尾。
You在还原 stty
states时也需要应用相同的重定向。否则,在恢复阶段仍然会出现Invalid argument
或ioctl故障……
正确的行动方针:
saved_tty_settings="$(stty -g < /dev/tty)"
# ...do terminal-changing stuff...
stty "$saved_tty_settings" < /dev/tty
这是我测试的实际脚本;我将整个脚本重写为一个经典的Bourne shell脚本:
#!/bin/sh
# This is sttytest.sh
# This backs up current terminal settings...
STTY_SETTINGS="`stty -g < /dev/tty`"
echo "stty settings: $STTY_SETTINGS"
# This reads from standard input...
while IFS= read LINE
do
echo "input: $LINE"
done
# This restores terminal settings...
if stty "$STTY_SETTINGS" < /dev/tty
then
echo "stty settings has been restored sucessfully."
fi
测试运行:
printf 'This\ntext\nis\nfrom\na\nredirection.\n' | sh sttytest.sh
结果:
stty settings: 2d02:5:4bf:8a3b:3:1c:7f:15:4:0:1:ff:11:13:1a:ff:12:f:17:16:ff:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0
input: This
input: text
input: is
input: from
input: a
input: redirection.
stty settings has been restored sucessfully.
使用Debian dash
0.5.7和GNU 8.13's stty
进行测试。
https://unix.stackexchange.com/questions/542937
复制相似问题