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.

1 Answer 1

3

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

trap 'printf "\nAborting\n"; exit 1' SIGINT
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. The problem I have with this solution is when I source the script with the function, it will also source the 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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.