我正在尝试创建一个简单的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
答案 0 :(得分: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是在stdin而不是在命令行上传递的,所以你也可以将echo
切换到cat
。
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
答案 1 :(得分:0)
变量需要放在双引号旁边才能展开。您还必须使用\
\"
引用带有双引号的实例,即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
。
{{1}}