如何将 sudo 与管道一起使用?

oro*_*oro 15 command-line scripts

可能重复:
sudo 和重定向输出

假设我想在 /etc/profile.d 中添加一些行。我尝试:

$ sudo echo "something" >> /etc/profile
bash: /etc/profile: Access forbidden
Run Code Online (Sandbox Code Playgroud)

我当然可以写:

$ sudo su
# echo "something" >> /etc/profile
Run Code Online (Sandbox Code Playgroud)

这有效,但它在 shell 脚本中不起作用。

那么,正确的方法是什么?

Eri*_*lho 14

您可以使用tee

$ echo "something" | sudo tee -a /etc/profile
Run Code Online (Sandbox Code Playgroud)

如果省略-a(append) 该文件将被覆盖。


And*_*ese 13

你的版本:

sudo echo "something" >> /etc/profile

在此命令中,echo以 root 身份运行,但将echo输出重定向到 root-only 文件的 shell仍以您的身份运行。这就是为什么您会收到“禁止访问”的原因

工作版本:

sudo bash -c 'echo "something" >> /etc/profile'

在此命令中,您使用 sudo 启动一个具有 root 权限的新 shell,然后使用 bash 的 -c 选项为该 shell 提供整个命令字符串(包括重定向)。