0

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

  1. is there a native way to perform it?
  2. 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

2
  • The commands in within $(...) are executed in a subshell. As such, exit is invoked for the subshell. Commented Jun 25, 2013 at 12:31
  • Thanks, Indeed duplicate! Commented Jun 25, 2013 at 12:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.