Another shell trick

Let's start with the solution instead of the problem:

myvar=$(myfunc) || exit $?

Assuming myfunc is a function defined elsewhere in your shell script this will execute that function and assign it's output to myvar. However when myfunc fails, the entire assignment statement fails with the exit status of myfunc, so you exit with the same exit status by using || exit $?.

It is really important to have this exit statment in there, even if myfunc already has it. You could look at the $(...) construct as a subshell, so the exit of myfunc only exits that subshell. This took me quite a while to figure out!

On a related note, you may know you can execute things in a subshell by using (list). If you do that any variables etc won't affect your current shell. However variables and hence also functions from the parent shell are usable in the subshell. Handy (and maybe obvious).