![](/img/trans.png)
[英]How to escape dollar sign on Docker-compose bash script command
[英]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 /空字符串,並且內容看起來不正確。 因為,當我嘗試安裝nginx時,我收到此錯誤:
http://nginx.org/packages/centos///repodata/repomd.xml:[Errno 14] HTTP錯誤404 - 未找到
有任何想法嗎?
原則上,使用語法就足夠了
cat >file <<EOL
$my_var
EOL
也就是說,按原樣使用變量,而不必轉義$
。
而不是
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
^ ^
說
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
來自man bash
:
這里的文件
這種類型的重定向指示shell從當前源讀取輸入,直到看到僅包含分隔符(沒有尾隨空白)的行。 然后,讀取到該點的所有行都將用作命令的標准輸入。
here-documents的格式是:
<<[-]word here-document delimiter
不對字執行參數擴展,命令替換,算術擴展或路徑名擴展。 如果引用單詞中的任何字符,則分隔符是單詞上的引號刪除的結果,並且不會展開here-document中的行。 如果word不加引號,則here-document的所有行都要進行參數擴展,命令替換和算術擴展 。 在后一種情況下,字符序列\\被忽略,\\必須用於引用字符\\,$和`。
看一個例子:
$ 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'
有一個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
如果引用單詞中的任何字符,則分隔符是單詞上的引號刪除的結果,並且不會展開here-document中的行。
只需將該字符串包裝成單引號即可
baseurl='http://nginx.org/packages/centos/$releasever/$basearch/'
然后美元符號將被視為通常的字符。
[root@xxx ~]# cat test
baseurl='http://nginx.org/packages/centos/$releasever/$basearch/'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.