The function GetValue
along with printing a string to stdout also returns a code 1
. So assignment to the variable var1
from the function, though sets the value to foobar
, sets an exit code 1
which is a non-zero code causing the part after the ||
to be invoked.
But remember the same happens in the case with the declare
, but the reason you see Successed
is because the exit code 1
from the function is suppressed when the declare
built-in acts on the variable. So
var2="$(GetValue)" # sets a non-zero exit code 1
declare var2 # sets a success exit code 0
Since the last foreground command's exit code is the one used in the evaluation of success/failure, the part after &&
, which is echo "Successed!"
gets invoked.
So, your claim of using declare
in the variable assignment makes a difference in the exit code is incorrect, because these two still remain the same as they both set the exit code 1
which triggers the false case.
var1="$(GetValue)" && echo "Successed!" || echo "Failed!";
var2="$(GetValue)" && echo "Successed!" || echo "Failed!";
Suggest to always separate the initialization/declaration when using the built-ins local
, declare
and export
var=5
declare -i var
is preferred over declare -i var=5
.
See Why does local
/declare
sweep the return code of a command? for more reference on the subject.