Create file with contents from shell script

BashShell

Bash Problem Overview


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>

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

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.

Solution 3 - Bash

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

Solution 4 - Bash

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUKBView Question on Stackoverflow
Solution 1 - BashamsView Answer on Stackoverflow
Solution 2 - Bashsampson-chenView Answer on Stackoverflow
Solution 3 - BashnullrevolutionView Answer on Stackoverflow
Solution 4 - BashSergejView Answer on Stackoverflow