[英]Why is my bash script breaking on an empty space?
我有一個shell腳本,它打破了Virtualhost和*之間的第42行空間。 因此,唯一與控制台相呼應的是
<VirtualHost
我想要發生的是我的整個字符串被回顯到控制台。
<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>
這是我的腳本供參考:
#!/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
您需要將變量放在雙引號中以展開它們而不進行單詞拆分和通配符擴展。
checkFileForString "$currentFile" "$currentRegex" "$newText"
您的腳本中的另一個問題是replaceStringInFile()
函數。 變量僅在雙引號內擴展,而不是單引號。 所以它應該是:
sed -i -e "s|${2}|${3}|" "$1"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.