在 CentOS linux bash 脚本中回显写入文件时转义美元符号

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

我正在编写一个 bash 脚本,需要在此位置创建一个文件:

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

内容如下:

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

所以,我试过这样做:

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

当我检查文件的内容时,我看到以下内容:

如您所见,美元符号未被转义,因此变量被评估为 null/empty 字符串,内容看起来不正确。因为,当我尝试安装 nginx 时,出现此错误:

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

有什么想法吗?

原则上用句法就可以了

cat >file <<EOL
$my_var
EOL

即按原样使用变量,不转义$

所以不用

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

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

来自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 `.

看例子:

$ 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

让我们运行它:

$ 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'

只需将该字符串用单引号引起来

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

然后美元符号将被视为普通字符。

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

有一个 here-doc 通用语法来防止内容被扩展,就像在变量周围放置单引号时那样:

cat<<'EOF' 

:

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

来自

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.