从 shell 脚本创建包含内容的文件

我如何在 shell 脚本中创建一个名为 foo.conf 的文件并使其包含:

NameVirtualHost 127.0.0.1


# Default
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>
74739 次浏览

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

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.

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

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!