如何使用sudo将输出重定向到我没有写权限的位置? [英] How do I use sudo to redirect output to a location I don't have permission to write to?
问题描述
我已经在我们的开发RedHat linux机器上获得了sudo访问权限,而且我似乎经常需要将输出重定向到我通常没有写权限的位置.
I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.
麻烦的是,这个人为的例子不起作用:
The trouble is, this contrived example doesn't work:
sudo ls -hal /root/ > /root/test.out
我刚刚收到回复:
-bash: /root/test.out: Permission denied
如何使它正常工作?
推荐答案
您的命令不起作用,因为重定向是由您的Shell执行的,该Shell没有写/root/test.out
的权限. sudo不会执行输出的重定向.
Your command does not work because the redirection is performed by your shell which does not have the permission to write to /root/test.out
. The redirection of the output is not performed by sudo.
有多种解决方案:
-
使用sudo运行shell并使用
-c
选项向其发出命令:
sudo sh -c 'ls -hal /root/ > /root/test.out'
使用命令创建脚本并使用sudo运行该脚本:
Create a script with your commands and run that script with sudo:
#!/bin/sh
ls -hal /root/ > /root/test.out
运行sudo ls.sh
.如果您不想创建临时文件,请参见Steve Bennett的 answer .
Run sudo ls.sh
. See Steve Bennett's answer if you don't want to create a temporary file.
使用sudo -s
启动外壳,然后运行命令:
Launch a shell with sudo -s
then run your commands:
[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
使用sudo tee
(如果使用-c
选项时必须逃避很多):
Use sudo tee
(if you have to escape a lot when using the -c
option):
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
需要重定向到/dev/null
才能停止 tee 从输出到屏幕. 追加,而不是覆盖输出文件
(>>
),tee -a
或tee --append
(最后一个特定于 GNU coreutils ).
The redirect to /dev/null
is needed to stop tee from outputting to the screen. To append instead of overwriting the output file
(>>
), use tee -a
or tee --append
(the last one is specific to GNU coreutils).
感谢访问 Jd , Adam J. Forster 和 Johnathan .
这篇关于如何使用sudo将输出重定向到我没有写权限的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!