1

Let's assume I have the following function:

#!/usr/bin/env bash

f(){
    trap 'printf "\nAborting\n"; return 1' SIGINT
    sleep 10
    return 0
}

If I run f and wait those 10 seconds and then do

$ echo $?
> 0

That's expected. But if I run f and hit Ctrl+c, the function f is aborted, but

$ echo $?
> 0

instead of 1. I assume I'm not trapping properly, but don't how to fix it.

Jolta
  • 2,620
  • 1
  • 29
  • 42
pfnuesel
  • 14,093
  • 14
  • 58
  • 71

1 Answers1

3

You must use exit instead of return. So this would be

trap 'printf "\nAborting\n"; exit 1' SIGINT
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • 1
    Thanks. The problem I have with this solution is when I source the script with the function, it will also source the [tag:trap] condition, i.e. when I hit `Ctrl+c`, it will close my shell. The solution, of course, is to *not* source the script, but I tried to make the script also working for users that will source it. – pfnuesel Nov 28 '13 at 13:09
  • As long as you have the trap inside a function, the function will be parsed, of course, but not executed. Consequently, the trap will not be active, unless you call the function. – Olaf Dietsche Nov 28 '13 at 14:55