当echo写入CentOS linux bash脚本中的文件时,转义美元符号

我正在处理需要在此位置创建文件的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

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

enter image description here

如您所见,美元符号未被转义,因此该变量被评估为null /空字符串,并且内容看起来不正确.因为,当我尝试安装nginx时,我收到此错误:

07001: [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:

06003

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'
相关文章
相关标签/搜索