How to Make a Variable is Unexpanded in the Heredoc

We have a script which using a heredoc. We need to be able to write unexpanded variables in the heredoc. We want only the $domain_name would be expanded.

#!/bin/bash
domain_name='bonguides.me'
cat << EOF >> default.conf
server {
    listen 80;
    server_name $domain_name www.$domain_name;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }
}
EOF

When we ran the script, as you can see we’re able to pass bonguides.me as vibrable into the file but $uri and $query_string are removed.

# ./installer.sh
# cat default.conf
server {
    listen 80;
    server_name bonguides.me www.bonguides.me;

    location / {
        try_files  / /index.php?;
    }
}

We need only the variable $domain_name to be expanded and the $uri and $query_string still remain.

To dealing with that, you need add a before any variable that you don’t want to be expanded in a heredoc. So, the script should be look like below:

#!/bin/bash
domain_name='bonguides.me'
cat << EOF >> default.conf
server {
    listen 80;
    server_name $domain_name www.$domain_name;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }
}
EOF

We’ve edited then run the script again, and now it works as expected.

# ./installer.sh
# cat default.conf
server {
    listen 80;
    server_name bonguides.me www.bonguides.me;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
}

Leave a Comment

Required fields are marked *