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

很多时候我只是想添加一些东西 /etc/hosts 或类似的文件,但最终无法,因为两者 >>> 不允许,即使有root。

有没有办法让这项工作无需 su 或者 sudo su 进入根目录?

有帮助吗?

解决方案

使用 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

其他提示

问题是 shell 确实输出重定向,而不是 sudo 或 echo,因此这是以普通用户身份完成的。

尝试以下代码片段:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

问题是你的 shell 负责处理重定向。它试图用以下命令打开文件 你的 权限不是您在 sudo 下运行的进程的权限。

也许使用这样的东西:

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

正在做

sudo sh -c "echo >> somefile"

应该管用。问题是 > 和 >> 是由您的 shell 处理的,而不是由“sudoed”命令处理的,因此权限是您的权限,而不是您“sudoing”的用户的权限。

我想指出,出于好奇,您还可以引用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"

在 bash 中你可以使用 tee 结合 > /dev/null 保持标准输出干净。

 echo "# comment" |  sudo tee -a /etc/hosts > /dev/null

使用 尤的回答, ,把这个放入你的 ~/.bashrc:

sudoe() {
    [[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
    echo "$1" | sudo tee --append "$2" > /dev/null
}

现在你可以运行 sudoe 'deb blah # blah' /etc/apt/sources.list


编辑:

更完整的版本,允许您通过管道输入或从文件重定向,并包括 -a 切换以关闭附加(默认情况下处于打开状态):

sudoe() {
  if ([[ "$1" == "-a" ]] || [[ "$1" == "--no-append" ]]); then
    shift &>/dev/null || local failed=1
  else
    local append="--append"
  fi

  while [[ $failed -ne 1 ]]; do
    if [[ -t 0 ]]; then
      text="$1"; shift &>/dev/null || break
    else
      text="$(cat <&0)"
    fi

    [[ -z "$1" ]] && break
    echo "$text" | sudo tee $append "$1" >/dev/null; return $?
  done

  echo "Usage: $0 [-a|--no-append] [text] <file>"; return 1
}

您还可以使用 sponge 来自 moreutils 包并且不需要重定向输出(即,没有 tee 隐藏噪音):

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

回声'Hello world'| (sudo tee -a /etc/apt/sources.list)

这对我有用:原始命令

echo "export CATALINA_HOME="/opt/tomcat9"" >> /etc/environment

工作指令

echo "export CATALINA_HOME="/opt/tomcat9"" |sudo tee /etc/environment

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

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

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

sed 选项解释:

  • -我 对于就地
  • $ 最后一行
  • A 用于追加

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

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

像这样的东西对你有用吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top