In case of export
, the return value of mycmd
is ignored, and export
will always return true.
This may prevent conditionals, set -e
and traps from working correctly.
export foo="$(mycmd)"
Hence, when by performing export
and assignment separately, the return value of the assignment will be that of mycmd
. This avoids the problem.
foo="$(mycmd)"
export foo
Exceptions: If you intend to ignore the return value of an assignment, you can either ignore this warning or use:
foo=$(mycmd) || true
export foo
There is no warning for export foo=bar
because bar
is a literal and not a command substitution with an independent return value. It also does not warn about local -r foo=$(cmd)
, where declaration and assignment must be in the same command.
Similarly in case of local
,
local foo="$(mycmd)"
local foo
foo=$(mycmd)
The exit status of the command is overridden by the exit status of the creation of the local variable. For example:
$ f() { local foo=$(false) || echo foo; }; f
$ f() { local foo; foo=$(false) || echo foo; }; f
foo
Also in case of readonly
,
readonly foo="$(mycmd)"
foo="$(mycmd)"
readonly foo