如何使用sudo将输出重定向到我没有写权限的位置? [英] How do I use sudo to redirect output to a location I don't have permission to write to?

查看:106
本文介绍了如何使用sudo将输出重定向到我没有写权限的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我们的开发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 -atee --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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆