102

How do I, in a shell script, create a file called foo.conf and make it contain:

NameVirtualHost 127.0.0.1

# Default
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>

4 Answers 4

169

Use a "here document":

cat > foo.conf << EOF
NameVirtualHost 127.0.0.1

# Default
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>
EOF
Sign up to request clarification or add additional context in comments.

4 Comments

@ams Can one have variables that get interpreted within the document?
Yes. How it's interpreted depends on what quotes you put around the EOF.
For those using it inside an indented code section, the text and the final EOF should not be indented and be at the beginning of the line.
Example of variable interpolation. Variable declaration earlier in file: my_var="foo". Reference inside EOF heredoc: $my_var will resolve to foo.
37

You can do that with echo:

echo 'NameVirtualHost 127.0.0.1

# Default
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>' > foo.conf

Everything enclosed by single quotes are interpreted as literals, so you just write that block into a file called foo.conf. If it doesn't exist, it will be created. If it does exist, it will be overwritten.

2 Comments

This works, but is limited by the maximum command line length.
Also it only works as long as you don't have apostrophes in the document.
11

a heredoc might be the simplest way:

cat <<END >foo.conf
NameVirtualHost 127.0.0.1

# Default
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>
END

1 Comment

Same as the accepted answer with the only difference that it shows that the <<END delimiter can come before the redirection >foo.conf. Which version one finds more readable is a matter of personal preference of course.
7

This code fitted best for me:

sudo dd of=foo.conf << EOF
<VirtualHost *:80>
  ServerName localhost
  DocumentRoot /var/www/localhost
</VirtualHost>
EOF

It was the only one I could use with sudo out of the box!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.