这是一个非常简单的问题,至少看起来应该是这样,关于Linux中的sudo权限。

很多时候,我只是想在/etc/hosts或类似的文件中添加一些内容,但最终无法添加,因为>和>>都不允许,即使使用root。

有没有什么方法可以让这个工作,而不需要su或sudo su到root?


当前回答

echo 'Hello World' | (sudo tee -a /etc/apt/sources.list)

其他回答

使用tee—append或tee -a。

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list

注意不要在引号里加引号。

为了避免将数据打印回控制台,请将输出重定向到/dev/null.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null

记住(-a/——append)标志! tee就像>一样,会覆盖你的文件。Tee -a的工作方式类似于>>,将写入文件的末尾。

你可以改变文件的所有权,然后在使用cat >>追加后将其更改回来吗?

sudo chown youruser /etc/hosts  
sudo cat /downloaded/hostsadditions >> /etc/hosts  
sudo chown root /etc/hosts  

这样的东西对你有用吗?

sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"

通过使用sed -i和$ a,可以在最后一行之后附加文本,其中包含变量和特殊字符。

例如,将$NEW_HOST和$NEW_IP添加到/etc/hosts:

sudo sed -i "\$ a $NEW_IP\t\t$NEW_HOST.domain.local\t$NEW_HOST" /etc/hosts

Sed选项说明:

-i for in-place $ for最后一行 A表示追加

我想指出的是,对于好奇的人来说,你也可以引用一个heredoc(对于大的区块):

sudo bash -c "cat <<EOIPFW >> /etc/ipfw.conf
<?xml version=\"1.0\" encoding=\"UTF-8\"?>

<plist version=\"1.0\">
  <dict>
    <key>Label</key>
    <string>com.company.ipfw</string>
    <key>Program</key>
    <string>/sbin/ipfw</string>
    <key>ProgramArguments</key>
    <array>
      <string>/sbin/ipfw</string>
      <string>-q</string>
      <string>/etc/ipfw.conf</string>
    </array>
    <key>RunAtLoad</key>
    <true></true>
  </dict>
</plist>
EOIPFW"