0

我正在尝试创建一个简单的 shell 脚本,以使我更容易在本地 MAMP Web 开发环境中添加/设置新站点。我有以下脚本,但是需要添加到我的 VHOSTS.conf 文件末尾的文本包含双引号,并且在尝试写入文件时会引发错误。当需要附加的字符串包含双引号时,如何将文本添加到文件末尾?

clear

echo "Enter the name of the dev site you want to add (ie: mysite.dev): "
read devname
echo "Enter the name of the directory where your site lives (ie: /Volumes/Clients/AIA/Website/Dev/): "
read directory
echo "$directory is what you typed in. Your record will be added"

echo '<VirtualHost *:8888>
ServerName $devname
DocumentRoot "$directory"
<Directory "$direcotry">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>' >> /Applications/MAMP/conf/apache/vhosts.conf

echo ""
echo "Your record has successfully been added for $devname
4

2 回答 2

1

变量插值在单引号内不起作用。您可以使用双引号,然后使用 . 转义字符串内的引号\"

echo "<VirtualHost *:8888>
ServerName $devname
DocumentRoot \"$directory\"
<Directory \"$directory\">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>" >> /Applications/MAMP/conf/apache/vhosts.conf

或者,对于长的多行字符串,您可能更喜欢 heredoc 语法。<<TOKEN您可以在开头和结尾分隔一个长字符串TOKEN,其中TOKEN是一些任意单词。它使您可以自由使用单引号和双引号,而无需转义它们。

Heredocs 在标准输入上而不是在命令行上传递,因此您还可以echocat.

cat >> /Applications/MAMP/conf/apache/vhosts.conf <<CONF
<VirtualHost *:8888>
ServerName $devname
DocumentRoot "$directory"
<Directory "$directory">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
CONF
于 2013-09-13T14:30:12.640 回答
0

变量需要放在双引号周围才能展开。您还只需使用\ie在其中使用双引号实例引用它们\"

echo "<VirtualHost *:8888>
ServerName $devname
DocumentRoot \"$directory\"
<Directory \"$direcotry\">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>" >> /Applications/MAMP/conf/apache/vhosts.conf
于 2013-09-13T14:20:33.590 回答