我正在尝试将多行写入文本文件,如下所示:
cat <<EOT >> /etc/apache2/sites-available/eco.conf
<VirtualHost *:80>
ServerName eco.vagrant
DocumentRoot /var/www/eco/website/public
<Directory var/www/eco/website/public/>
Options FollowSymLinks
AllowOverride All
</Directory>
# Logging
ErrorLog /var/log/apache2/eco-error.log
LogLevel notice
CustomLog /var/log/apache2/eco-access.log combined
</VirtualHost>
EOT
但是我明白
bash: /etc/apache2/sites-available/o-eco.conf: Permission denied
所以我尝试了
sudo cat...
但还是一样。
我很喜欢这样,而不是一行,因为它在 bash 脚本中,我可以清楚地看到将用缩进等编写的内容。
我应该用什么工具来这样写?或者我应该如何在这里使用 cat ?
如果你这样做
sudo cat <<EOT >>filename
,输出重定向发生在你的原始shell中,而不是在超级用户进程中,所以它仍然会失败。您需要通过显式执行 shell 将重定向移至超级用户进程。
sudo bash -c 'cat <<EOT >>/etc/apache2/sites-available/eco.conf
<VirtualHost *:80>
ServerName eco.vagrant
DocumentRoot /var/www/eco/website/public
<Directory var/www/eco/website/public/>
Options FollowSymLinks
AllowOverride All
</Directory>
# Logging
ErrorLog /var/log/apache2/eco-error.log
LogLevel notice
CustomLog /var/log/apache2/eco-access.log combined
</VirtualHost>
EOT
'
避免处理额外引用的一个简单方法是将heredoc提供给
sudo tee
,例如:
sudo tee -a /path/to/file >&- <<EOT
...
EOT
tee filename
取代 > filename
tee -a filename
取代 >> filename
>&-
(或 >/dev/null
)可防止复制所有 tee
写入到 stdout
。