44

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?

54

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.)

  • So if one is setting a variable from a literal, and there's no exit code to discard, there's nothing wrong with doing it all on one line. – Monty Harder Apr 17 '18 at 17:59
  • 1
    As far as this shellcheck error is concerned, no. But as now-deleted answers got half-right between them, the Bourne shell did not support the assignment syntax for export, so for some years there was received wisdom about doing this if one's interpreter was likely to be the Bourne shell. – JdeBP Apr 17 '18 at 18:53
  • @JdeBP, note that the Bourne shell did support foo=$(cmd) export foo, though with the same caveat that cmd's exit status is lost (but did cause the shell to exit if failing with set -e). – Stéphane Chazelas Apr 18 '18 at 14:40
  • That was covered by my first sentence. – JdeBP Apr 19 '18 at 5:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.