Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I can setup trap in bash scripts but not bash functions.

For example, source the code below and run f, now try Ctrl+C, it's not been trapped!

How to setup trap in bash functions?

  4 trap ctrl_c INT
  6 ctrl_c () {
  7  echo "** Trapped CTRL-C"
  8 }
 11 f () {
 12   for i in `seq 1 100`; do
 13     sleep 1
 14     echo -n "."
 15   done
 16 } 
share|improve this question

That's because it sends SIGINT to the process in the foreground instead of to bash (which is running the script). If you want to do this, make the function asynchronous and then use wait (which will act as expected and use the trap).

share|improve this answer
It kind of works. But I found that if f is in a pipe echo 123 | f, then it's not trapping? – Cheng Dec 25 '11 at 14:48
@Cheng Use a subshell (and a pipe in this case is unnecessary anyway, just use a heredoc/herestring). (command | command) & – Chris Down Dec 25 '11 at 17:11

I think you should make the function global

trap ctrl_c INT
ctrl_c () {
  echo "** Trapped CTRL-C"
for i in `seq 1 100`; do
  sleep 1
  echo -n "."
share|improve this answer
INT and SIGINT are synonymous -- it will make no difference. – Chris Down Dec 25 '11 at 12:11

Protip: Send the foreground process a QUIT with Ctrl-\ when Ctrl-C, -Z, -D aren't working.

Clear traps at the end of execution with trap - list of signals here

Fun on a non-production system: Try setting a trap for all sensible signals (e.g., not KILL). kill -l (not that's a lower-case L not a number 1 or pipe |)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.