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

标签 linux bash shell unix echo

我有一个 shell 脚本,它在第 42 行的 Virtualhost 和 *.结果,唯一回显到控制台的是

<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"

关于linux - 为什么我的 bash 脚本在空白处中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18789687/

相关文章:

arrays - Bash 数组 : Unexpected Syntax error

string - 为什么 echo "Hello World!"语句没有按预期工作?

为文件/目录树创建结构

linux 对话框 --checklist 错误

linux - 如何在文件中间写入(Bourne Shell 脚本)

linux - ls 在 linux 脚本中有条件地循环

c - 第二个 getpwuid 调用似乎覆盖了旧值

linux - 将部分字符串转换为另一个字符集

c - bash 无法使用 setuid 程序获得 root 权限

linux - SCP从远程服务器传输在特定时间后修改的文件