这个问题似乎与 a specific programming problem, a software algorithm, or software tools primarily used by programmers 无关.如果您认为该问题将成为 another Stack Exchange site 上的主题,您可以发表评论,说明在哪里可以回答问题。
关闭去年。
我在我们的一个开发 RedHat linux 机器上获得了 sudo 访问权限,我似乎发现自己经常需要将输出重定向到我通常没有写入权限的位置。
问题是,这个人为的例子不起作用:
sudo ls -hal /root/ > /root/test.out
我刚刚收到回复:
-bash: /root/test.out: Permission denied
我怎样才能让它工作?
最佳答案
您的命令不起作用,因为重定向是由您的 shell 执行的,它没有写入 /root/test.out
的权限。输出的重定向不是由sudo执行的。
有多种解决方案:
使用 sudo 运行 shell 并使用 -c
选项向它发出命令:
sudo sh -c 'ls -hal /root/ > /root/test.out'
使用您的命令创建一个脚本并使用 sudo 运行该脚本:
#!/bin/sh
ls -hal /root/ > /root/test.out
运行 sudo ls.sh
。参见 Steve Bennett 的 answer如果您不想创建临时文件。
使用 sudo -s
启动一个 shell,然后运行你的命令:
[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
使用 sudo tee
(如果你在使用 -c
选项时必须转义很多):
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
需要重定向到 /dev/null
才能停止 tee从输出到屏幕。 追加而不是覆盖输出文件
(>>
),使用 tee -a
或 tee --append
(最后一个特定于 GNU coreutils )。
感谢 Jd , Adam J. Forster和 Johnathan用于第二、第三和第四种解决方案。
https://stackoverflow.com/questions/82256/