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

标签 linux bash nginx heredoc

我正在编写需要在此位置创建文件的 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 时,出现了这个错误:

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'

关于linux - 在 CentOS linux bash 脚本中回显写入文件时转义美元符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34538635/

相关文章:

android - 从命令行打开 Android 应用程序并与之交互

python - 从 Python 运行 Perl 脚本并将输出写入文件时,为什么文件是空的?

Linux:函数可以用作符号链接(symbolic link)的源吗?

amazon-web-services - Nginx URL限制502网关

mysql - nginx-tornado-django 请求超时

mysql - 如何从AWS的快照或实例中提取数据?

用于测量磁盘 i/o 等的 Linux 工具

linux - 提取分区数的最佳方法?

Linux:用 Lua 表现奇怪的 tput cup

macos - nginx 在本地主机上抛出 403,可能是由于 OS X High Sierra?