0

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?

3
  • Just a syntax error: It must be if [ 5 -gt 4 ] ; ... Commented May 8, 2019 at 8:41
  • tldp.org/LDP/abs/html/comparison-ops.html Commented May 8, 2019 at 8:42
  • 1
    Thank you for pointing that out! Trying to make a stupid test case I actually wrote a very stupid test case as I am still new to bash scripting. It works like a charm now. Thank you for the helpful referrence too! Commented May 8, 2019 at 8:52

1 Answer 1

1

[ is a synonym for test, so [ 5>4 ] is equal to test 5>4. Bash reads this command as run test and redirect file descriptor 5 to a file named 4, and without arguments test exits with 0. See bash manual#Redirections for further information.

You should have noticed that a file named 4 is created in your working directory btw.

Sign up to request clarification or add additional context in comments.

1 Comment

I completely forgot about redirection, thank you for pointing that out!

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.