为什么我的 bash 脚本在空白处中断



我有一个 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="<VirtualHosts[*]:80>s+DocumentRoots/Applications/MAMP/htdocs/webs+ServerNamesweb.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"

最新更新