Selectively ignoring Ctrl+C / SIGINT

3

2

I have the following bash compound command:

while true ; do slow-command-one ; slow-command-two ; slow-command-three ; done

What happens:

  • When I press CtrlC at any point, the entire command is aborted.

What I want to happen:

  • When I press CtrlC during execution of slow-command-two, slow-command-two should be aborted, and execution should continue with slow-command-three.
  • When I press CtrlC at any other time, the entire command should be aborted (as now).

How do I get this to happen?

dave4420

Posted 2010-11-05T10:57:35.023

Reputation: 1 328

2Ctrl-C is SIGINT. – Ignacio Vazquez-Abrams – 2010-11-05T11:03:24.437

Ta, have edited. – dave4420 – 2010-11-05T11:09:15.290

Answers

6

You can use trap command for that. Catch SIGINT with it and Ctrl+C does not hurt your command execution. Then reset trap to default settings.

This should work:

#!/bin/bash

while true; do
  slow-command-one;
  trap "echo Proceeding to command three" SIGINT;
  slow-command-two;
  trap - SIGINT;
  slow-command-three;
done

Janne Pikkarainen

Posted 2010-11-05T10:57:35.023

Reputation: 6 717