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

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


In principle, it suffices to use a syntax

cat >file <<EOL$my_varEOL

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.shr="hello"cat - <<EOLhello$rEOLecho "double quotes"cat - <<"EOL"hello$rEOLecho "single quotes"cat - <<'EOL'hello$rEOL

And let's run it:

$ bash a.shhellohello              <-- it expands when unquoteddouble quoteshello$r                 <-- it does not expand with "EOL"single quoteshello$r                 <-- it does not expand with 'EOL'


There's an here-doc generic syntax to prevent the content to be expanded like when you put single quotes around variables :

cat<<'EOF' 

:

cat<<'EOF' > /path/to/file[nginx]name=nginx repobaseurl=http://nginx.org/packages/centos/$releasever/$basearch/gpgcheck=0enabled=1EOF

From

man bash | less +/here-doc

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.


Just wrap that string into single quotes

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

Then the dollar sign would be treated as a usual character.

[root@xxx ~]# cat testbaseurl='http://nginx.org/packages/centos/$releasever/$basearch/'