0

I currently use many heredocs in bash scripts.

These heredocs contain bash variables, e.g. ${MY_VAR}, which are substituted as the script executes and the heredoc is read.

Some of these heredocs have grown to hundreds of lines long, and so I would like to put these in their own files.

Unfortunately this breaks the variable substitution. I could add boilerplate to each file, turning each file into its own bash script (containing their own heredoc, which uses environment variables). This feels like pointless complexity.

Is there a way of making bash perform variable substitution on an external file as it is read in?

6
  • 2
    Take a look at envsubst command. Commented Jun 25, 2024 at 8:23
  • @Philippe Thanks for the suggestion. I've read that envsubst requires me to export all the needed variables, and that it doesn't handle escaped variables which need to remain variables. e.g. \${foo} Have I understood correctly? Commented Jun 25, 2024 at 8:28
  • You don't have to use explicitly export. Try MY_VAR=$MY_VAR envsubst '${MY_VAR}' < heredoc.txt. For the escaping, you can try '\$MY_VAR' to differentiate $MY_VAR from ${MY_VAR} Commented Jun 25, 2024 at 9:17
  • Always include a minimal reproducible example with concise, testable sample input, expected output and your code attempt to solve your problem in every question. See How to Ask. Commented Jun 25, 2024 at 9:43
  • You could use php, erb, or some templating lib like mustache Commented Jun 25, 2024 at 14:17

1 Answer 1

1

Assuming you fully trust these files, one option is to write a function that reads the file and adds the boilerplate that you mention, and then use the source built-in with process substitution to execute the result inside the main script's execution environment.

That is, something like this:

function boilerplatify() {
  local varname="$1"
  local filepath="$2"
  echo "$varname=<<EOF"
  cat -- "$filepath"
  echo EOF
}

source <(boilerplatify my_var /path/to/template)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.