Bash Trap – How to Trap ‘Ctrl + c’ for Bash Script but Not for Process Open in This Script

bashtrap:

I tried to have an interactive program in a bash script :

my_program

And I wish to be able to close it with 'Ctrl + c'.
But when I do it my script is closing as well.

I know about.

trap '' 2
my_program
trap 2

But in this case, I just can't close my_program with Ctrl + c.

Do you have any idea how to allow Ctrl + c on a program, but not closing the script running it ?

EDIT : add example

#!/bin/bash
my_program
my_program2

If i use Ctrl + c to close my_program, my_program2 is never executed because the whole script is exited.

Best Answer

You should use trap true 2 or trap : 2 instead of trap '' 2. That's what "help trap" in a bash shell says about it:

If ARG is the null string each SIGNAL_SPEC is ignored by the shell and by the commands it invokes.

Example:

$ cat /tmp/test
#! /bin/sh
trap : INT
cat
echo first cat killed
cat
echo second cat killed
echo done
$ /tmp/test
   <press control-C>
^Cfirst cat killed
   <press control-C>
^Csecond cat killed
done
Related Question