thebiggestlebowski
thebiggestlebowski

Reputation: 2799

bash function non-zero exit code

In the function "handleExit" below, the exitCode is zero, ie, "0". i want it to be "1". My function called "exit 1". What do I need to do in order to detect that the function "writeToErr" had a non-zero status.

#!/bin/bash

set -euo pipefail

logError() {
  awk " BEGIN { print \"$@\" > \"/dev/fd/2\" }"
}

function writeToErr ()  {
    echo "standard out"
    logError "standard err"
    exit 1
}

function wrapper () {
    writeToErr >>output.log 2>&1
}

function handleExit () {
    echo "handle exit"
    exitCode=$?
    if [ $exitCode -eq "0" ]
     then
        echo "No problem"
     else
        echo "$0 exited unexpectedly with status:$exitCode"
        exit 1
     fi
}

trap wrapper EXIT
handleExit >>output.log 2>&1

And here are the contents of "output.log":

handle exit
No problem
standard out
standard err

Upvotes: 0

Views: 3991

Answers (1)

that other guy
that other guy

Reputation: 123690

There are two problems:

  1. You run handleExit before you run wrapper, so it hasn't failed yet.
  2. handleExit checks the exit code of echo

Without a description of what you're trying to do, I'm guessing you wanted:

#!/bin/bash

set -euo pipefail

logError() {
    # A better way to write to stderr
    echo "$*" >&2
}

function writeToErr ()  {
    echo "standard out"
    logError "standard err"
    exit 1
}

function wrapper () {
    writeToErr >>output.log 2>&1
}

function handleExit () {
    # Get exit code of the previous command, instead of echo
    exitCode=$?
    echo "handle exit"
    if [ $exitCode -eq "0" ]
     then
        echo "No problem"
     else
        echo "$0 exited unexpectedly with status:$exitCode"
        exit 1
     fi
}

# Call handler on exit, so it has something to handle
trap handleExit EXIT
wrapper

Upvotes: 4

Related Questions