2

I'm using bash script, I'm trying to exit from a function in child shell script to parent shell script with returning status code.

Script1.sh
echo "hello script1"
. ./script2.sh
echo $?

Script2.sh
status()
{
    echo "status"
    return 1
}
status
echo "Hello shell2"

This script prints "status" and "Hello shell2", but I want to exit from status function of script2.sh to script1.sh without printing "Hello shell2".

I have checked some questions in stack overflow those talks about return from child script to parent and not from function of child to parent.

Thanks In Advance, Soman

1 Answer 1

3

You can't specify how many levels "up" to return, but you can respond to the exit status of the call. Just let status return as it currently does, and since you are sourcing the file, change the call to status to

status || return

This will cause the sourced script to return to the parent if status has a non-zero exit status.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your reply. In our script, we have "status" function is called from many places inside different functions. Is there is a different approach to handle this scenario
Afraid not. It's even more complicated if status can be called at an arbitrary depth in the call stack, since my answer assumes you are calling status at the script level, not inside another function.
Thanks, I will try to figure out different approach.

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.