Ответ 1
Функции оболочки действительно не имеют "возвращаемых значений", просто выходят из кода.
Вы можете добавить && :
к вызывающему, это делает команду "проверено" и не выйдет из нее:
foo() {
echo 'x'
return 42
}
out=$(foo && :)
echo $out
:
- это "нулевая команда" (т.е. ничего не делает). В этом случае он даже не выполняется, так как он запускается только в том случае, если foo
возвращает 0 (а это не так).
Выводится:
x
Это, возможно, немного уродливо, но опять же, все сценарии оболочки, возможно, немного уродливы; -)
Цитата sh(1)
из FreeBSD, которая объясняет это лучше, чем bash man-страница:
-e errexit
Exit immediately if any untested command fails in non-interactive
mode. The exit status of a command is considered to be explicitly
tested if the command is part of the list used to control an if,
elif, while, or until; if the command is the left hand operand of
an "&&" or "||" operator; or if the command is a pipeline preceded
by the ! operator. If a shell function is executed and its exit
status is explicitly tested, all commands of the function are con‐
sidered to be tested as well.