14

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
  5 
  6 ctrl_c () {
  7  echo "** Trapped CTRL-C"
  8 }
  9 
 10 
 11 f () {
 12   for i in `seq 1 100`; do
 13     sleep 1
 14     echo -n "."
 15   done
 16 } 
1
  • 2
    You may put an f at the end of your code, and removing the space from the f ().
    – GWF
    Dec 11, 2016 at 8:04

3 Answers 3

8

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).

2
  • 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, 2011 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, 2011 at 17:11
1

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 |)

0

I think you should make the function global

#!/bin/bash
trap ctrl_c INT
ctrl_c () {
  echo "** Trapped CTRL-C"
} 
for i in `seq 1 100`; do
  sleep 1
  echo -n "."
done
1
  • INT and SIGINT are synonymous -- it will make no difference.
    – Chris Down
    Dec 25, 2011 at 12:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .