3

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

2 Answers2

5

Capture the current status in the function:

bye() {
  local status=$?
  (( status == 1 )) && echo "Hello World!"
  echo "Exiting with status $status"
  exit $status
}
trap bye EXIT
# ...
exit $some_status
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
3

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Marco
  • 824
  • 9
  • 13