5

I'm looking for a way to set an exported environment variable in a Bash script to a default value specified literally in a script only if the environment variable was previously not set to any value (even an empty string), and to do this without mentioning the name of the environment variable more than once in the code that solves this task.

Note that the solutions here and here (using ${FOO:=42}) do not apply because they only set a shell variable, not an exported environment variable. I don't want to set it for a single command; I want to set it for all commands that follow from the same shell.

Also note that something like

export FOO="${FOO:-42}"

does not answer this question either as it mentions FOO twice in the solution.

I realize this question has an easy technical alternative solution — just use the solution that mentions the variable name twice. To be explicit, "no, that cannot be done" is a reasonable answer to this question, if it is indeed not possible, and those alternatives are perfectly fine if it's not a problem to mention the variable twice, so it's a slightly artificial problem (I only care about this to make editing the script slightly more clean and easy).

chepner
  • 497,756
  • 71
  • 530
  • 681
Manuel Gómez
  • 63
  • 2
  • 4
  • I'm voting to close this question as off-topic because it is about code golf, not practical programming. – John Zwinck May 07 '18 at 12:31
  • You can wrap a block of `: ${FOO:=42}` assignments in `set -a`/`set +a`, in which block all assignments automatically set the export attribute on the assigned name. – chepner May 07 '18 at 13:27
  • DRY is a practical programming principle and avoiding such repetition actually avoids opportunities for introducing bugs during refactoring. This is to provide a script with multiple options that need to come from environment variables and have default values. If a variable is added or renamed in the future, it's easy to accidentally change the variable name only once, and then you have a bug. This is not about minimizing code size and this is not about code golf. – Manuel Gómez May 08 '18 at 10:36

1 Answers1

7

The -a shell option automatically exports a variable when you assign to it.

set -a
: ${FOO:=42}
: ${BAR:=baz}
set +a

You do need to take care that none of the variables so tested are created prior to the block. If BAR has a value but is not yet exported, the expansion alone is not sufficient to set BAR's export attribute; it has to be created or modified.

chepner
  • 497,756
  • 71
  • 530
  • 681