Reputation: 10812
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?
Upvotes: 1
Views: 5057
Reputation: 241721
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 $VAR
s should be replaced with their values <<'ENDOFCONTENT'
would prevent the parameter replacement.
Upvotes: 5
Reputation: 95634
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.
Upvotes: 1