6

I have an unexpected behaviour- following snippet fail with 'unbound variable' error:

#!/bin/bash
set -u
<<EOF
a=a
b=$a
EOF

Tested on:
GNU bash, version 4.4.12(1)-release
GNU bash, version 4.2.46(2)-release

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
padura
  • 123

1 Answers1

13

What you have defined with set -u is force an exit with an error message, if attempted to use undefined variable (The set builtin command).

The form of here-documents << with EOF is equivalent to as if double-quoting the words inside to allow the variables to be expanded (parameter expansion) by the shell (bash in this case; also subject to command substitution and arithmetic expansion). To avoid the expansion from happening quote the here-string with a single quote

set -u
<<'EOF'
a=a
b=$a
EOF
Inian
  • 12,807