Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
up vote 3 down vote accepted

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.

share|improve this answer
    
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 – Soman Mar 26 '14 at 11:53
    
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. – chepner Mar 26 '14 at 12:01
    
Thanks, I will try to figure out different approach. – Soman Mar 26 '14 at 12:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.