我已经在我们开发的一个RedHat linux机器上获得了sudo访问权,我似乎发现自己经常需要将输出重定向到一个我通常没有写访问权的位置。
问题是,这个人为的例子不起作用:
sudo ls -hal /root/ > /root/test.out
我刚刚收到回复:
-bash: /root/test.out: Permission denied
我怎样才能让它工作呢?
我已经在我们开发的一个RedHat linux机器上获得了sudo访问权,我似乎发现自己经常需要将输出重定向到一个我通常没有写访问权的位置。
问题是,这个人为的例子不起作用:
sudo ls -hal /root/ > /root/test.out
我刚刚收到回复:
-bash: /root/test.out: Permission denied
我怎样才能让它工作呢?
当前回答
sudo at now
at> echo test > /tmp/test.out
at> <EOT>
job 1 at Thu Sep 21 10:49:00 2017
其他回答
也许你只被授予sudo访问一些程序/路径?那就没办法做你想做的事了。(除非你能破解)
如果不是这样,那么也许你可以编写bash脚本:
cat > myscript.sh
#!/bin/sh
ls -hal /root/ > /root/test.out
按ctrl + d:
chmod a+x myscript.sh
sudo myscript.sh
希望能有所帮助。
写一个脚本怎么样?
Filename: myscript
#!/bin/sh
/bin/ls -lah /root > /root/test.out
# end script
然后使用sudo运行脚本:
sudo ./myscript
刚才有人建议sudo tee:
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
这也可以用于将任何命令重定向到您没有访问权限的目录。它之所以有效,是因为tee程序实际上是一个“回显到文件”程序,重定向到/dev/null是为了阻止它也输出到屏幕,以保持它与上面最初的人为示例相同。
每当我要做这样的事情时,我就变成root:
# sudo -s
# ls -hal /root/ > /root/test.out
# exit
这可能不是最好的方法,但确实有效。
您的命令不起作用,因为重定向是由您的shell执行的,shell没有写入/root/test.out的权限。输出的重定向不是由sudo执行的。
有多种解决方案:
Run a shell with sudo and give the command to it by using the -c option: sudo sh -c 'ls -hal /root/ > /root/test.out' Create a script with your commands and run that script with sudo: #!/bin/sh ls -hal /root/ > /root/test.out Run sudo ls.sh. See Steve Bennett's answer if you don't want to create a temporary file. 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]$ 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 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的第二,第三和第四个解决方案。