Patroclus
Patroclus

Reputation: 1232

How to prevent a user from using ctrl-c to stop a script?

I load a script in .bash_profile and this script will ask for right password whenever a user opens a terminal window. If the user enters a wrong code, the script will run exit to stop the current terminal.

if [ $code = "980425" ]; then
    echo hello
else
    exit
fi

But I realize that the user can always use ctrl-c to stop the script and enter the terminal. How to avoid that?

Upvotes: 9

Views: 10136

Answers (2)

Jens
Jens

Reputation: 72746

You can always trap SIGINT:

trap 'echo got SIGINT' INT

Once you're done, reinstall the default handler again with

trap INT

See the POSIX spec for trap for details. This works in all Bourne shells, not just bash.

Note that while Bash accepts SIGINT for the signal name, many Bourne shells require the name to be just INT.

Upvotes: 20

Heidi Negrete
Heidi Negrete

Reputation: 51

You can use:

trap '' 2 
commands
trap 2

This disables signal 2 (control c) and then re-enables it after the command has run.

Upvotes: 5

Related Questions