Why is my bash script breaking on an empty space?

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

I have a shell script that is breaking on a space on line 42 between Virtualhost and the *. 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

回答1:

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. Variables are only expanded inside double quotes, not single quotes. So it should be:

sed -i -e "s|${2}|${3}|" "$1"


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!