I have this issue in sh a function is required to exit the entire script stuck OR echo a value that will be set to a variable by the caller.
I think that the following example explains the problem the best:
#!/bin/sh
do_exit(){
if [ "$1" = "1" ] ; then
echo "name"
return 0
fi
exit 1
}
echo "# That of course should pass"
echo before
var=$(do_exit 1)
echo $var
echo after
echo ""
echo "# Here I expect the func to terminate the script"
echo before
var=$(do_exit 2)
echo $var
echo after
echo ""
echo "# Here I also expect the func to terminate the script"
echo before
var=`do_exit 2`
echo $var
echo after
echo ""
echo "# And this is the only case it exit"
echo before
do_exit 2
echo after
And the output for above is:
# That of course should pass
before
name
after
# Here I expect the func to terminate the script
before
after
# Here I also expect the func to terminate the script
before
after
# And this is the only case it exit
before
How could you explain that? It seems to me like the function is executed in a forked process that terminates it self but not the caller
- is there a native way to perform it?
- Is there other way to do it beside passing argument by reference as already explained here: Bash - Passing arguments by reference?
Thanks in advance! Yaniv