问题

我已经在我们的一个开发RedHat linux盒子上获得了sudo访问权限,我似乎经常需要将输出重定向到一个通常不具有写访问权限的位置.

麻烦的是,这个设计的例子不起作用:

sudo ls -hal /root/ > /root/test.out

我刚收到回应:

-bash: /root/test.out: Permission denied

如何才能使此功能正常运作?



解决方法

您的命令不工作,因为重定向由您的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 了解第二,第三和第四个解决方案.




相关问题推荐