gpt4 book ai didi

bash - 从使用读取和陷阱的 bash 脚本中清除退出

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

运行下面的脚本
按 Ctrl+C
观察当前的终端行为。
按几次 enter 并尝试执行一些命令。

#!/bin/bash
LOCK_FILE=/tmp/lockfile
clean_up(){
# Perform program exit housekeeping
echo -e "Signal Trapped, exiting..."
# Do some Special operation
rm -f $LOCK_FILE
#
exit 1
}

touch LOCK_FILE
trap clean_up SIGHUP SIGINT SIGTERM
read -s -p "Password: " var
echo -e "\n Input Password is: $var\n"

我想知道我做错了什么?
我尝试做一个干净的退出。它正在工作,但在退出终端后 STDIN 消失。

最佳答案

read -s 禁用本地回显(根据文档)如果您 ctrl-c 从读取中读取它无法重置本地回显的终端模式。比较中断读取前后 stty -a 的输出以查看它所做的更改(查看 echo* 模式)。

您可以使用reset(根据 Plutox 的评论)或手动重新启用本地 echo 模式以“修复”问题。

$ stty -a
speed 38400 baud; rows 46; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff
-iuclc -ixany imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke
$
$ cat t.sh
#!/bin/bash
clean_up(){
# Perform program exit housekeeping
echo -e "Signal Trapped, exiting..."
# Do some Special operation
rm -f $LOCK_FILE
#
exit 1
}

trap clean_up SIGHUP SIGINT SIGTERM
read -s -p "Password: " var
echo -e "\n Input Password is: $var\n"
$
$ sh t.sh
Password: Signal Trapped, exiting...
# I ran `stty -a` here but the lack of local echo means it didn't show up.
$ speed 38400 baud; rows 46; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff
-iuclc -ixany imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten -echo echoe -echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke

关于bash - 从使用读取和陷阱的 bash 脚本中清除退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24611716/

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