2

i want to exit from a shell script. it is a function that i call in a another function

i do this:

exit_script()
{
    if [[ $? -eq 0 ]] ; then
        echo "exit from script with success"
        exit
    else
        echo "exit with error..."
        exit
    fi
}

Is this correct to put "exit" or I must put an exit status after "exit" like "exit 1"?

3 Answers 3

3

exit without an argument uses the exit status of the preceding command. That's OK for the first case, but in the second case you should be exiting with a non-zero exit status (1 is OK for non-specific errors), not the 0 you get from the preceding echo.

exit_script()
{
    if [[ $? -eq 0 ]] ; then
        echo "exit from script with success" >&2
        exit  # or exit 0, if you want to be specific
    else
        echo "exit with error..." >&2
        exit 1
    fi
}

You probably want the messages to go to standard error, but if not, just remove the >&2 that I added to each call to echo.

If you want to exit with the same exit status that you are testing, you'll need to save it first.

exit_script()
{
    status=$?
    if [[ $status -eq 0 ]] ; then
        echo "exit from script with success"
    else
        echo "exit with error..."
    fi >&2
    # Now you can just make one, all-purpose call to exit
    exit $status
}
Sign up to request clarification or add additional context in comments.

Comments

0

Exit will copy the exit status of the last command called unless you provide it with an explicit value. In your case, Both exits will return success because the echos were successful.

Comments

0

exit status should be 0 on successful execution and non-zero if there were any errors.

Also note that when there are no parameters to exit,the exit status of the script is the exit status of the last command executed in the script (previous to the exit).

Comments

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.