Bash While-Loop – Prevent Ctrl+C from Interrupting

bash

Given this loop:

while sleep 10s ; do
  something-that-runs-forever
done

When I press Ctrl+C the whole while-loop gets interrupted. What I want to do is to interrupt the "something"-process, let 10 seconds pass, and then restart "something".

How do I make ctrl+c only affect "something", and not the while-loop?

EDIT: "interrupt" as in SIGINT. Kill. Abort. Terminate. Not "interrupt" as in "pause".

Best Answer

It should work if you just trap SIGINT to something. Like : (true).

#!/bin/sh
trap ":" INT    
while sleep 10s ; do
    something-that-runs-forever
done

Interrupting the something... doesn't make the shell exit now, since it ignores the signal. However, if you ^C the sleep process, it will exit with a failure, and the loop stops due to that. Move the sleep to the inside of the loop or add something like || true to prevent that.

Note that if you use trap "" INT to ignore the signal completely (instead of assigning a command to it), it's also ignored in the child process, so then you can't interrupt something... either. This is explicitly mentioned in at least Bash's manual:

If arg is the null string, then the signal specified by each sigspec is ignored by the shell and commands it invokes. [...] Signals ignored upon entry to the shell cannot be trapped or reset.

Related Question