BASH: Ctrl+C during input breaks current terminal

2019-07-12 23:38发布

My Bash version is: GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu).

I have a piece of code like this:

   while true; do
        echo -n "Set password: "
        read -s pass1
        printf "\n"
        echo -n "Repeat password: "
        read -s pass2
        printf "\n"
        if [ $pass1 != $pass2 ]; then
            echo "Not same."
        else
            break
        fi
    done

If I exit this script with ctrl+c while on the line reading pass2 my terminal stops working properly.

user@host:~/bin$ user@host:~/bin$ user@host:~/bin$ user@host:~/bin$No command 'aaaa' found, did you mean...

Everything gets written to the same line and my typing is not echoed. I use Putty for these connections. When I connect to host again everyting is working again.

This problem only appears when certain conditions are true: Only if it is run with sudo. Both normal user and root (became root with sudo -s) can exit the script without problem.

This problem exists only during second read statement. Exiting while reading pass1 variable causes no trouble.

What could be the reason for this problem?

1条回答
相关推荐>>
2楼-- · 2019-07-12 23:41

Resetting your terminal should help. read -s is changing some settings to hide the input, and in some cases these settings aren't restored after the interrupt signal is received. Add this line to the beginning of the script to make sure your script resets the terminal to a good state:

trap 'stty sane' INT

As pointed out by User112638726, you should rather save the state of your terminal at the beginning of the script, and restore that (rather than assuming the original state is identical to what sane produces).

original_tty_state=$(stty -g)
trap "stty $original_tty_state" INT
查看更多
登录 后发表回答