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

前端 未结 15 1463
情深已故
情深已故 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 08:00

    The problem is that the command gets run under sudo, but the redirection gets run under your user. This is done by the shell and there is very little you can do about it.

    sudo command > /some/file.log
    `-----v-----'`-------v-------'
       command       redirection
    

    The usual ways of bypassing this are:

    • Wrap the commands in a script which you call under sudo.

      If the commands and/or log file changes, you can make the script take these as arguments. For example:

      sudo log_script command /log/file.txt
      
    • Call a shell and pass the command line as a parameter with -c

      This is especially useful for one off compound commands. For example:

      sudo bash -c "{ command1 arg; command2 arg; } > /log/file.txt"
      

提交回复
热议问题