I was wondering if there any way to create a here document in bash to output to a file within a script, problem is that in this config file I am trying to output some variables that start with $ I want to substitute, while others I do not.

Let me illustrate:

cat >> /opt/apache2/sites-available/$WEBSITENAME <<END-OF-FILE
 ServerName $WEBSITENAME #This I want to replace

<VirtualHost *:80>

 ServerName $WEBSITENAME # And this
 ServerAlias *.xxx.com

RedirectMatch /(.*) https://$WEBSITENAME/$1 # But not the $1 here

 CustomLog /var/log/apache2/access.log combined


This is one of many examples, I have many other config files that I want to substitute variables in, but they themselves have many variables of their own, so I don't want to substitute those.


You can escape the $, forcing bash to treat it as a literal character rather than the start of a variable.

You do this with the backslash (\) character.

So use this,:

RedirectMatch /(.*) https://$WEBSITENAME/\$1

in the here document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.