linuxbashbash-trap

How to trap on exit 1 only in bash


I have the following bash script:

#!/bin/bash


function hello {
    echo "Hello World!"
}

trap hello EXIT

The problem is that this function will execute on any exit code for that script. if I append an exit 1 at the end of the script, Hello World! will be printed, but it also will get printed on exit 0.

Is there a way to run a function within a script, but only if the script exits with exit code 1 only? (actually anything other than 0 works too.)


Solution

  • This will work, but with losing the exit code in the function:

    trap '[[ $? -eq 1 ]] && hello' EXIT
    

    If you need the exit code in the function, you have to do the test inside the function.