dotplan

troubleshooting & performance analysis

Returning values from shell functions, and the non-exit thereof.

Tags:

So, I wanted to write a (bash) shell function that returned a value to the calling routine, rather than set a global variable. I found that the following would do what I wanted
#!/bin/bash

func() {
echo "This is the return value:"
return
}

 

x=$(func "param")
echo "The return value is : $x"

And this is what we see

lovebox:tmp gjl$ ./simple.sh
The return value is : This is the return value:

However, what I wanted to do was to catch an error, and exit the script completely from within the function. All the documentation available tells that using ‘exit’ at any point in the script (including from within a function) will exit the whole script.

However, that does not happen in the above case, if we replace return with ‘exit’ then the function should not return – because we use ‘exit’ and the whole script should imediately halt.
func() {
echo "This is the return value:"
exit
}

x=$(func "param")
echo "The return value is : $x"

This however is what we see

lovebox:tmp gjl$ ./simple.sh
The return value is : This is the return value:

The ‘exit’ has behaved exactly the same as ‘return’ which is not expected. The reason is that when we use the format
x=$(func )
which we need to get a real return value, rather than just an exit code, the shell creates a subshell, because what we are effectively doing is doing command substitution, like using `ls` but using our own shell function rather than another program like “ls”. So when we use ‘exit’ it does not exit the ‘main’ script, just the subshell that the function was running in.

© 2009 dotplan. All Rights Reserved.

This blog is powered by Wordpress and Magatheme by Bryan Helmig.