0

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
2
  • Get your code checked at shellcheck.net Commented Feb 21, 2018 at 0:11
  • @codeforester Thanks for the site. Unfortunately, it didn't catch the errors and pointed out something that is ok. Commented Feb 21, 2018 at 5:25

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you - much appreciated!

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.