Linux Question

Bash write into file that is named by a variable

I am working on creating a simple script to make it easy to set up a virtual host on Apache server. Currently I don't seem to be able to write the config file because it's in a variable. How do I get around it. Here is my code that does not work.

echo "creating conf file"
echo "<VirtualHost *:80>" >> $siteConf
echo "ServerName *.$domain" >> $siteConf
echo "DocumentRoot $publicHtmlLoc" >> $siteConf
echo "DirectoryIndex index.php" >> $siteConf
echo "ServerAlias $" >> $siteConf
echo "</VirtualHost>" >> $siteConf

I am running the script with the bash command.

Edit: The Error i get is this

$siteConf: ambiguous redirect

Domain comes from here:

echo "Write websiter url, no sub dir allowed"
read -p "Name: " domain

As suggested in comments its the path that is wrong, i tried to echo out the variable and i can see it has removed the '.' chars from some reason and left a space instead, why would the script do that ?

Was using IFS earlier in the script, to split the the domain name

Answer Source

The code looks as if it should work. You might do better with

echo "<VirtualHost …>"
echo "</VirtualHost>"
} > $siteConf 

(or >> $siteConf if you really want to add to the existing file). That does a single redirection for all the output, and truncates the file. It is also a good idea as a general rule to enclose uses of variables in double quotes:

} > "$siteConf"

Basic debugging for shell scripts:

  • What do you get from bash -x

You get 'ambiguous redirect' when the variable named doesn't exist or is empty, or if it expands to two or more words. That suggests that the first line of your script isn't an accurate representation of what you've got, but it is hard to guess how you've got it wrong. Misspelled name, or an unwanted space are probably the most likely, but it could be something else.

Alright looks like I needed to wrap it like in quotes like in the answer Getting an 'ambiguous redirect' error that antak suggested.

That's a good question to cross-reference. At one point, this question was closed as a duplicate of it, but the issue here turned out to be about IFS being set, which is not an alternative source of trouble identified in that other question.

Have you gone messing with IFS at any point in the script?

Yes — been doing IFS for splitting the URL into parts.

Note that:

set_with_spaces="name1 name2"
echo Hi >> $set_with_spaces


 bash: $set_with_spaces: ambiguous redirect too.

Two names were generated from one variable.

$ IFS=.
$ domain=abc.def.ghi.jkl
$ echo $domain
abc def ghi jkl
$ echo "$domain"
$ IFS=$' \t\n'
$ echo $domain

If you have been messing with IFS, then its current value is probably altering how the names are being interpreted. Reinstate it to its default value (blank, tab, newline):

IFS=$' \t\n'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download