Dipankar
Dipankar

Reputation: 141

Clean exit from bashscript which uses read and trap

Run the below script
Press Ctrl+C
Observe the current terminal behaviour.
Press enter few times and try to execute some commands.

#!/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"

I wonder what is the mistake I am doing?
I try to do a clean exit. It is working but after exit terminal STDIN vanishes.

Upvotes: 3

Views: 2369

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

read -s disables local echo (as per the documentation) if you ctrl-c out of that read it fails to reset the terminal modes for local echo. Compare the output from stty -a before and after the interrupted read to see the changes it made (look at the echo* modes).

You can use reset (as per Plutox's comment) or manually re-enable the local echo modes to "fix" the problem.

$ 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

Upvotes: 3

Related Questions