goe
goe

Reputation: 5435

Exit entire program from a function call in shell?

I have a function which I use in my shell script and based on a certain condition I'd like to call "exit 0" in that function so that the entire script exits. But for some reason the program still runs after calling exit 0 in the function. Why?

check()
{
    printf "Would you like to try again?\n"
    read S
    if [ "$S" = "y" ]
    then 
        ./myprog
    else    
        exit 0  
    fi
}

And I call it like this:

if test $WRONG -eq 7
then
    printf "Sorry\n"
    check
fi

Upvotes: 1

Views: 4283

Answers (4)

Beel
Beel

Reputation: 1030

I agree with digitalross that something outside of what you're showing us is causing this behavior. exit 0 WILL exit the current process. so somehow check() is running in a separate child process that is exiting. Do you have code outside of this call that is invoking?

BTW, which OS and shell are you running?

You can force a parent to exit via something like (syntax depends on your shell)

check() || exit $?

Bill

Upvotes: 0

Roger Pate
Roger Pate

Reputation:

What you have works for me:

$ cat test-shell-exit
#!/bin/sh
check()
{
    printf "Would you like to try again?\n"
    read S
    if [ "$S" = "y" ]
    then
        echo Try again
    else
        echo Done
        exit 0
    fi
}
echo Before
check
echo After

$ ./test-shell-exit 
Before
Would you like to try again?
y
Try again
After

$ ./test-shell-exit 
Before
Would you like to try again?
n
Done

Could you try this test case and update your answer with any differences from it? It appears the problem you're running into is caused by something you haven't mentioned.


Update: Example of using a loop instead of calling your program again:

$ cat test-shell-exit 
#!/bin/sh
check()
{
    printf "Would you like to try again?\n"
    read S
    if [ "$S" = "y" ]
    then
        echo Try again
    else
        echo Done
        exit 0
    fi
}
while true; do
    echo Before
    check
    echo After
done

$ ./test-shell-exit 
Before
Would you like to try again?
y
Try again
After
Before
Would you like to try again?
y
Try again
After
Before
Would you like to try again?
n
Done

Upvotes: 2

DigitalRoss
DigitalRoss

Reputation: 146221

I was expecting to find your code exiting a subshell, but I don't see any reason for that, the code looks OK, and it seems to run as expected for me.

So my guess is that either you are not reading a y when you think you are not, or you are really doing the exit 0 and have just missed noticing it in your test results.

When you say "the program still runs" do you mean "the shell program still runs after calling the check procedure"?

Upvotes: 0

Marc B
Marc B

Reputation: 360842

Without any code to go by, I'd guess that your function is invoking a sub-shell, and it's that sub-shell which is exit()ing, and not the parent shell running the main script.

Upvotes: 0

Related Questions