I'm trying to add cleanup to some existing bash scripts, their functionality relevant to this question is that they create a log file and have multiple exit statements. What I am trying to achieve is move the log file before the script exits and then exit with the same code that the original exit was invoked with, one way of doing this I've found is with trap, I've written a simple script that catches the code:
#!/bin/bash
cleanup() {
exit_code=$?
echo trapped exit, code=$exit_code
trap 'exit 0' EXIT
}
trap cleanup EXIT
exit 4
If you run the script it echoes the correct exit code and exits with it. However if instead of
exit 4
I have the call to exit in an if/while loop like:
if [ 5>4 ] ; then
exit 4
fi
I get exit code 0.
Is there a way to achieve my goal using trap or is there an alternative?
if [ 5 -gt 4 ] ; ...