How do I use sudo to redirect output to a location I don't have permission to write to?

前端 未结 15 1426
情深已故
情深已故 2020-11-22 07:23

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 h

相关标签:
15条回答
  • 2020-11-22 07:42
    sudo at now  
    at> echo test > /tmp/test.out  
    at> <EOT>  
    job 1 at Thu Sep 21 10:49:00 2017  
    
    0 讨论(0)
  • 2020-11-22 07:47

    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.

    There are multiple solutions:

    • 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).

    Thanks go to Jd, Adam J. Forster and Johnathan for the second, third and fourth solutions.

    0 讨论(0)
  • 2020-11-22 07:50

    How about writing a script?

    Filename: myscript

    #!/bin/sh
    
    /bin/ls -lah /root > /root/test.out
    
    # end script
    

    Then use sudo to run the script:

    sudo ./myscript
    
    0 讨论(0)
  • 2020-11-22 07:53

    I would do it this way:

    sudo su -c 'ls -hal /root/ > /root/test.out'
    
    0 讨论(0)
  • 2020-11-22 07:55

    The way I would go about this issue is:

    If you need to write/replace the file:

    echo "some text" | sudo tee /path/to/file
    

    If you need to append to the file:

    echo "some text" | sudo tee -a /path/to/file
    
    0 讨论(0)
  • 2020-11-22 07:56

    Don't mean to beat a dead horse, but there are too many answers here that use tee, which means you have to redirect stdout to /dev/null unless you want to see a copy on the screen.

    A simpler solution is to just use cat like this:

    sudo ls -hal /root/ | sudo bash -c "cat > /root/test.out"
    

    Notice how the redirection is put inside quotes so that it is evaluated by a shell started by sudo instead of the one running it.

    0 讨论(0)
提交回复
热议问题