4

I'm trying to run the command envsubst < myfile to replace environment variables but instead of being replaced with their values, they are being replaced with blank strings.

Here's my example command (split onto separate lines for clarity):

SIGNOFF="Goodbye"
&&
printf "\nOkay, \$SIGNOFF has been set to \"$SIGNOFF\"\n\nOriginal contents:\n\n"
&&
cat test.conf
&&
printf "\n\nContents after envsubst < test.conf\n\n"
&&
envsubst < test.conf | cat
&&
printf "\n\n"

Here are my results:

$ SIGNOFF="Goodbye" && printf "\nOkay, \$SIGNOFF has been set to \"$SIGNOFF\"\n\nOriginal contents:\n\n" && cat test.conf && printf "\n\nContents after envsubst < test.conf\n\n" && envsubst < test.conf | cat && printf "\n\n"

Okay, $SIGNOFF has been set to "Goodbye"

Original contents:

Hello world, let's change the variable in the quotes below to say Goodbye!
"$SIGNOFF" (it certainly shouldn't just be blank!)

Contents after envsubst < test.conf

Hello world, let's change the variable in the quotes below to say Goodbye!
"" (it certainly shouldn't just be blank!)

$ 

I'm clearly doing something obvious wrong, I just have a silly suspicion it's one of those things that is so obvious that I must be overly complicating my own google searches in trying to find an answer

apbarratt
  • 615
  • 9
  • 18

1 Answers1

5

The variable is not exported, so it's not visible to any command. Export it.

SIGNOFF="Goodbye"
export SIGNOFF
envsubst < file
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Excellent, had to be something obvious like that didn't it! =D Right then, so I'd better have a think, because my true environment is inside a docker which is bringing in this variable from a .env file. I wonder if that same .env file can have the export keyword stuck in there too, will give it a go :) – apbarratt Jun 09 '21 at 15:34
  • Thank you for the incredibly fast reply by the way, I'll select as answer the moment when it allows me to =D – apbarratt Jun 09 '21 at 15:35
  • 2
    You don't need to put `export` in your `.env`; use `set -a` to enable auto-export before sourcing it, and `set +a` to turn that back off when no longer needed (environment variables use the same limited pool of space that's also used for command-line arguments, so you don't want to export shell variables that don't need to be in the environment, or else you'll be reducing the maximum allowed command-line length unnecessarily). – Charles Duffy Jun 09 '21 at 15:48