A few questions about the sample script below.
I'm calling a function _foo
and want to capture the output of it into a variable $bar
, but also use the return status (which may not be 0
or 1
), or failing that have exit
stop the script (when non-zero).
- Why doesn't the
exit
in function_foo
work when called this way? (if ! bar="$(_foo)"
). It works when called "normally".- the
exit
will stop the script if I change the if statement to this (but I lose its output):if ! _foo ; then
- the
exit
behaves likereturn
and will not stop the script:if ! bar="$(_foo)" ; then
- Just calling a function without the assignment and an exit will work, however calling it like
var="$(func)"
doesn't.
- the
- Is there a better way to capture the output of
_foo
into$bar
from the function as well as use return status (for other than0
or1
, eg acase
statement?)
I have a feeling I may need to use trap
somehow.
Here's a simple example:
#!/usr/bin/env bash
set -e
set -u
set -o pipefail
_foo() {
local _retval
echo "baz" && false
_retval=$?
exit ${_retval}
}
echo "start"
if ! bar="$(_foo)" ; then
echo "foo failed"
else
echo "foo passed"
fi
echo "${bar}"
echo "end"
Here's the ooutput:
$ ./foo.sh
start
foo failed
baz
end
Here's some more examples:
This will exit:
#!/usr/bin/env bash
set -e
set -u
set -o pipefail
func() {
echo "func"
exit
}
var=''
func
echo "var is ${var}"
echo "did not exit"
This will not exit:
#!/usr/bin/env bash
set -e
set -u
set -o pipefail
func() {
echo "func"
exit
}
var=''
var="$(func)"
echo "var is ${var}"
echo "did not exit"