Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping dollar sign when echo write to file in CentOS linux bash script

I am working on a bash script that needs to create a file in this location:

/etc/yum.repos.d/nginx.repo

with the following contents:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

So, I have tried to do it like this:

cat >/etc/yum.repos.d/nginx.repo <<EOL
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=0
enabled=1
EOL

When I check the contents of the file, I see the following:

enter image description here

As you can see, the dollar sign weren't getting escaped, so the variable was evaluated to null/empty string and the contents do not look correct. Because, when I try to install nginx, I get this error:

http://nginx.org/packages/centos///repodata/repomd.xml: [Errno 14] HTTP Error 404 - Not Found

Any ideas?

like image 514
Latheesan Avatar asked Dec 25 '22 11:12

Latheesan


1 Answers

In principle, it suffices to use a syntax

cat >file <<EOL
$my_var
EOL

That is, use the vars as they are, without escaping $.

So instead of

baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
                                         ^            ^

say

baseurl=http://nginx.org/packages/centos/$releasever/$basearch/

From man bash:

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \ is ignored, and \ must be used to quote the characters \, $, and `.

See an example:

$ cat a.sh
r="hello"
cat - <<EOL
hello
$r
EOL

echo "double quotes"
cat - <<"EOL"
hello
$r
EOL

echo "single quotes"
cat - <<'EOL'
hello
$r
EOL

And let's run it:

$ bash a.sh
hello
hello              <-- it expands when unquoted
double quotes
hello
$r                 <-- it does not expand with "EOL"
single quotes
hello
$r                 <-- it does not expand with 'EOL'
like image 95
fedorqui 'SO stop harming' Avatar answered Feb 17 '23 18:02

fedorqui 'SO stop harming'