Tags
Tags

Reputation: 172

Why is trap command not seeing exit code?

Im having issues where the EXIT Trap command is not seeing my exit code. Ive tried just setting a $var from 0 to 1 and right now I'm trying to override the exit with a 1 and base on that having the trap command run certain code.

#!/bin/bash

if [[ 0 -ge 1 ]]; then
    echo "run code"
else
    echo "oops.. dont like what I see"
    exit 1
fi

finish() {
    sleep 5
    term=$?
    if [[ $term -eq 0 ]]; then
        echo pass
    else
        echo fail
    fi
}
trap 'finish' EXIT

When I troubleshoot the code. term is being assign to 0 when exit is triggered.

Upvotes: 1

Views: 931

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295815

Two issues here:

  • Because the trap 'finish' EXIT line is at the bottom of the script, any exit command which is invoked before execution reaches that point will not honor the trap.

    To address this, move the finish function's declaration, and the trap command activating it, above the first point in the script where an exit might occur

  • Because the sleep 5 is immediately above the term=$?, it overrides the value of $? which might have otherwise been set. Be sure to capture $? before running any commands which might change it.

Upvotes: 1

Related Questions