Home > front end >  exception handling in korn shell
exception handling in korn shell

Time:06-10

I recently stumbled across some shell script code which is repeatedly doing the same thing over again and I was wondering if this could be a bit simplified.

Basically in a defined function, after each and every call the return code is checked. If it is not 0, some outputs are done and the function exits prematurely. In this cases we willfully use return to escape the function but do not want to stop the whole process by using exit.

e.g.:

function _myFunc {
  typeset ret=0
  
  _myFirstSubFunc "TEST"
  ret=$?
  if [[ $? -ne 0 ]]; then
     echo "myFirstSubFunc produced an error: $ret"
     return $ret
  fi

  _mySecondSubFunc "TEST"
  ret=$?
  if [[ $? -ne 0 ]]; then
     echo "mySecondSubFunc produced an error: $ret"
     return $ret
  fi

  return $ret
}

I'd like to reduce this repeated code of

  • checking the return code
  • printing out some information if the returncode is != 0
  • stopping the current function from continuing

to one call, so the code isn't that much cluttered with this checking. The execution of the function should continue if the previous call was successful.

Usually, when I'd like to abort (exit) the whole process, one function will do this trick. But when a value should be returned in the case of an error things get (at least for me) a bit tricky.

I tried to use traps or aliases, unfortunately without success. Additionally I'm limited to ksh88, so it seems I cannot use some conditionals following the call by using ||.

Any ideas, if there is something else so I can reduce this tedious error handling?

Thanks!

CodePudding user response:

function orReport {
  if "$@"; then
    return
  else
    ret=$?
    echo "$1 produced an error: $ret"
    return "$ret"
  fi
}

function _myFunc {
  orReport _myFirstSubFunc "TEST" || return
  orReport _mySecondSubFunc "TEST" || return
}
  • Related