Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 } 
share|improve this question
add comment

3 Answers

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? –  Golf November 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
add comment

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
share|improve this answer
    
INT and SIGINT are synonymous -- it will make no difference. –  Chris Down Dec 25 '11 at 12:11
add comment

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
add comment

Your Answer

 
discard

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.