【问题标题】:ubuntu: write multiple lines to a text file [closed]ubuntu:将多行写入文本文件[关闭]
【发布时间】:2017-05-28 08:01:47
【问题描述】:

我正在尝试将多行写入文本文件,如下所示:

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 ?

【问题讨论】:

  • 您没有写入文件的权限。语法无关紧要。
  • 这个问题更适合超级用户或 Linux SE 站点。

标签: bash ubuntu cat heredoc


【解决方案1】:

如果你做sudo cat &lt;&lt;EOT &gt;&gt;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
'

【讨论】:

    【解决方案2】:

    避免处理额外引用的一种简单方法是将您的命令传递给sudo tee,例如:

    cat <<EOT | sudo tee -a /path/to/eco.conf >&-
    ...
    EOT
    
    • | tee filename 替换 &gt;filename
    • | tee -a filename 替换 &gt;&gt;filename
    • 添加&gt;&amp;-(或&gt;/dev/null)会使tee 对写入stdout 的所有内容进行回显。

    【讨论】:

    • cat 的使用可以去掉:sudo tee -a /path/to/eco.conf &gt;&amp;- &lt;&lt;EOT
    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多