Bash – Why not to export variables on the same line you assign them

bash

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 of false is simply discarded. If you instead do

foo="$(false)"
export foo

the 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)". See pipefail in man 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 variables readonly before assigning them for the first time.)

Related Question