1

The following is a piece of content my bash script will write into the nginx configuration file.

WEBAPP=example.com
APPFOLDER=abcapp
CONFFILENAME=abc.conf

read -r -d '' FILECONTENT <<'ENDFILECONTENT'
server {
        listen 80;
        client_max_body_size 2M;
        server_name $WEBAPP;
        root /var/virtual/stage.$WEBAPP/current/src/$APPFOLDER/webroot;
}

ENDFILECONTENT
echo "$FILECONTENT" > /etc/nginx/sites-available/$CONFFILENAME

The code works successfully to write the content inside /etc/nginx/sites-available/abc.conf.

However, I have two bash variables in $WEBAPP and $APPFOLDER. They are manifested exactly like that inside the file instead of example.com and abcapp which is what I intended.

How do I make the script work as intended?

2
  • tldp.org/LDP/abs/html/here-docs.html Commented Jun 17, 2014 at 9:52
  • Do yourself a favor and forget read exists. It is rarely necessary and often misused. Commented Sep 6, 2014 at 5:24

2 Answers 2

5

bash allows newlines in quoted strings. It does parameter replacement (that is, $FOO gets replaced with the value of FOO) inside double-quoted strings ("$FOO") but not inside single-quoted strings ('$FOO').

So you could just do this:

FILECONTENT="server {
        listen 80;
        client_max_body_size 2M;
        server_name $WEBAPP;
        root /var/virtual/stage.$WEBAPP/current/src/$APPFOLDER/webroot;
}"
echo "$FILECONTENT" > /etc/nginx/sites-available/$CONFFILENAME

You don't really need the FILECONTENT parameter, since you could just copy directly to the file:

cat >/etc/nginx/sites-available/$CONFFILENAME <<ENDOFCONTENT
server {
        listen 80;
        client_max_body_size 2M;
        server_name $WEBAPP;
        root /var/virtual/stage.$WEBAPP/current/src/$APPFOLDER/webroot;
}
ENDOFCONTENT

In the second example, using <<ENDOFCONTENT indicates that the $VARs should be replaced with their values <<'ENDOFCONTENT' would prevent the parameter replacement.

Sign up to request clarification or add additional context in comments.

1 Comment

Do you mean cat instead of cp in your second example? On my machine, cat > bar <<< foo works, but cp > bar <<< foo doesn't.
1

You're actually deliberately turning off parameter subsitution by enclosing 'ENDFILECONTENT' in quotes. See this excerpt from example 19-7 of the advanced Bash scripting guide on Heredocs, slightly reformatted:

# No parameter substitution when the "limit string" is quoted or escaped.
# Either of the following at the head of the here document would have
# the same effect.
#
# cat <<"Endofmessage"
# cat <<\Endofmessage

Remove the single quotes around 'ENDFILECONTENT' and BASH will replace the variables as expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.