[英]Why is my bash script breaking on an empty space?
I have a shell script that is breaking on a space on line 42 between Virtualhost and the *. 我有一个shell脚本,它打破了Virtualhost和*之间的第42行空间。 As a result, the only thing that is echo'd to console is
因此,唯一与控制台相呼应的是
<VirtualHost
What I want to happen is for my entire string to be echo'd to the console. 我想要发生的是我的整个字符串被回显到控制台。
<VirtualHost *:80>
DocumentRoot /Applications/MAMP/htdocs/web
ServerName web.localhost
<Directory /Applications/MAMP/htdocs/web>
Options Indexes FollowSymLinks MultiViews +Includes
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
Here is my script for reference: 这是我的脚本供参考:
#!/bin/bash
# This script should be used to automate the web site installation
checkFileForString ()
{
# $1 = file
# $2 = regex
# $3 = text to be added
declare file=$1
declare regex=$2
declare file_content=$( cat "${file}" )
if [[ ! " $file_content " =~ $regex ]]; then
echo "$3" #>> $file
else
replaceStringInFile $file $regex $3
fi
}
replaceStringInFile ()
{
# $1 = file
# $2 = old string
# $3 = new string
sed -i -e 's|${2}|${3}|' $1
}
createFile ()
{
# $1 = file
declare fileToCheck=$1
if [ ! -f $fileToCheck ]; then
touch $fileToCheck
fi
}
# Add vhosts to httpd-vhosts.conf
echo "Adding vhosts to httpd-vhosts.conf"
currentFile="/Applications/MAMP/conf/apache/extra/httpd-vhosts.conf"
currentRegex="<VirtualHost\s[*]:80>\s+DocumentRoot\s/Applications/MAMP/htdocs/web\s+ServerName\sweb.localhost"
newText="<VirtualHost *:80>
DocumentRoot /Applications/MAMP/htdocs/web
ServerName web.localhost
<Directory /Applications/MAMP/htdocs/web>
Options Indexes FollowSymLinks MultiViews +Includes
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
"
checkFileForString $currentFile $currentRegex $newText
You need to put variables in double quotes to expand them without word splitting and wildcard expansion. 您需要将变量放在双引号中以展开它们而不进行单词拆分和通配符扩展。
checkFileForString "$currentFile" "$currentRegex" "$newText"
Another problem in your script is the replaceStringInFile()
function. 您的脚本中的另一个问题是
replaceStringInFile()
函数。 Variables are only expanded inside double quotes, not single quotes. 变量仅在双引号内扩展,而不是单引号。 So it should be:
所以它应该是:
sed -i -e "s|${2}|${3}|" "$1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.