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

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

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


当前回答

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

其他回答

sudo sh -c "echo >> somefile"

应该工作。问题是>和>>是由shell处理的,而不是由“sudoed”命令处理的,所以权限是您的,而不是您正在“sudo”进入的用户的权限。

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

我想指出的是,对于好奇的人来说,你也可以引用一个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"

你也可以使用海绵从moreutils包,不需要重定向输出(即,没有tee噪声隐藏):

echo 'Add this line' | sudo sponge -a privfile

有些用户在使用多条线路时不知道如何解决。

sudo tee -a  /path/file/to/create_with_text > /dev/null <<EOT 
line 1
line 2
line 3
EOT