Functions, exit, and kill in bash

Hello

Okay, for reasons related to sourcing a script from another script, I've had to put my main loop into a function, and from there I call other functions. My problem then is exiting from deep within the function call stack.

I used to simply call exit, and that would accomplish what I needed. But now, exit simply exits the function, and not the script. After a little experimentation, I found I could do the following:

function error_exit() {
  ec=$1
  print_error $1
  kill $$
}

And that accomplished the multi-level exit that I needed, but it doesn't allow me to return the correct error code to the user. It also will make it difficult to call this script from within another script, but that is not really a problem I care about at the moment. Any hints, this must be a common issue. I want the equivalent of C's exit behavior.

I just tried it:

#!/bin/bash

function asdf
{
        exit 2
}

function qwerty
{
        asdf
        exit 1
}

qwerty

It definitely exits with status 2, not status 1. If, in asdf, I source a script that calls exit with status 3, the entire script exits with status 3. So, I suspect there are issues elsewhere in your code preventing it from calling exit properly -- perhaps it's being called in a subshell, behind braces or pipes? Or perhaps you're not getting the shell you want.