Bash: Expanding variables and commands in text

2015-10-15

Say you have a text file with variables or commands in it:

        Today is $(date).
I have $n things to do.

Store text file contents in a variable and expand variables and commands in the text with:

# Init variables
      n=25
      # Store file in a variable
      text="$(echo EOF;cat $filename;echo EOF)"
      # Expand text (and print it to stdout)
      eval "cat <<$text"
      

That’s it! You will see something like:

Today is Thu Oct 15 12:04:56 JST 2015.
      You have 25 things to do.
      

Note, that without echo EOF bash will use first line of text as a limit string for heredoc.