从bash脚本中清除退出,该脚本使用read和trap

时间:2014-07-07 13:26:54

标签: bash shell terminal signals bash-trap

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

#!/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消失后。

1 个答案:

答案 0 :(得分:3)

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

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

$ 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