From What is the last argument of the previous command?
shellcheck tells you not to export variables on the same line you assign them.
I was wondering why?
Does the same advice apply to alias
, declare
, export
, local
, readonly
, and typeset
?
Best Answer
The problem is that in Bash every command has only one exit code. When you
export foo="$(false)"
the exit code offalse
is simply discarded. If you instead dothe failing first command can be acted upon, for example by the
errexit
setting.Declaring and assigning a string literal such as
export foo='bar'
does of course not suffer from this problem. But change is the only constant in software development, and it's simply good housekeeping to future-proof such statements by splitting them up.In addition to the assignment specific commands you mention there's also multiple commands in a single assignment such as
foo="$(false)$(true)"
. Seepipefail
inman bash
for yet another such trap.Another thing to remember is that the sequence of declaration and assignment is sometimes relevant. For example, you'll want to declare variables
local
before assigning them. (Unfortunately it's not possible to declare variablesreadonly
before assigning them for the first time.)