Carsten_Schmitz

How to use exit properly in UNIX shell scripts? (Solution inside!)

Discussion created by Carsten_Schmitz on Nov 14, 2017
Latest reply on Feb 6, 2018 by Carsten_Schmitz
Hi.

We have had an Automic Health Check(tm). The friendly consultant pointed out a minor problem to me that I'd never thought about, but it seems obvious in retrospective. I wonder if anyone has a good solution though.

Regular UNIX shell scripts oftentimes use "exit" with or without specifying a return code. For example, people may have shell script like this (this is just an example, I know it's not very practical!):

if [ $counter -lt 10 ] ; then
  counter=$counter++
else
  exit 1
fi

The intent is to exit the shell script with error code 1 at a specific point in the script. In principle, then, one gets that return code fed back into UC4, and can react to it further (e.g. 0 becomes ENDED_OK, any non-zero becomes ENDED_NOT_OK). This is generally though of as proper error handling.

However, here's the catch I never before considered: UC4 generates its own extra lines of shell script at the end of the job to call back to the agent (the so-called "Jobmelder"). If one exits the shell script prematurely with "exit", that code never runs. This is not the biggest deal, because the agent will eventually figure out that the job has ended anyway (by looking at the process table), but this may take up to an extra minute, it's not the most elegant way, and it apparently also prevents the submission of some statistics back into UC4. It would be much more desirable to have the final lines of UC4-added code called as intended, but still be able to end with a specific return code.

How does one do that?

Here's two things I considered that DON'T work:

  • "return" won't work, because "return" (in bash/ksh, which is what I am concerned with) does NOT work for the main script, but only for functions
  • manipulating the footer code does not work either, at least not cleanly, because you'd need to change it to exit in the very last line, after the Automic-added code has run, with an exit statement with a specific return code. One could make that change, but it would be overwritten on the next load of initial data. There is an include for user-supplied footer additions, but it's at the top of the footer, not at the end. So inserting some exit-handling code in there won't help, because then it would again exit BEFORE the final lines of UC4-generated code have run.
Cheers.

Outcomes