我正在编写需要在此位置创建文件的 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/空字符串,内容看起来不正确。因为,当我尝试安装 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/