Philippe
Philippe

Reputation: 26602

Ctrl-C doesn't always terminate a shell script

I have two scenarios:

#!/usr/bin/env bash
  
sleep infinity
# When I type Ctrl-C here, "sleep" command and script are stopped so I didn't see "End"

echo End
#!/usr/bin/env bash
  
docker exec container-id sleep infinity
# When I type Ctrl-C here, "docker exec" command is stopped but script continued so I saw "End"

echo End

Why the difference in behaviour?

Upvotes: 3

Views: 1012

Answers (1)

oguz ismail
oguz ismail

Reputation: 50775

That's how bash behaves when its process group receives a SIGINT but the program currently running on the foreground terminates normally.

The rationale for this behavior is given here as follows:

The basic idea is that the user intends a keyboard-generated SIGINT to go to the foreground process; that process gets to decide how to handle it; and bash reacts accordingly. If the process dies to due SIGINT, bash acts as if it received the SIGINT; if it does not, bash assumes the process handled it and effectively ignores it.

Consider a process (emacs is the usual example) that uses SIGINT for its own purposes as a normal part of operation. If you run that program in a script, you don't want the shell aborting the script unexpectedly as a result.

Upvotes: 5

Related Questions