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
I just receive the response:
-bash: /root/test.out: Permission denied
How can I get this to work?
How about writing a script?
Filename: myscript
Then use sudo to run the script:
Don't mean to beat a dead horse, but there are too many answers here that use
tee
, which means you have to redirectstdout
to/dev/null
unless you want to see a copy on the screen. A simpler solution is to just usecat
like this: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.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:Create a script with your commands and run that script with sudo:
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:Use
sudo tee
(if you have to escape a lot when using the-c
option):The redirect to
/dev/null
is needed to stop tee from outputting to the screen. To append instead of overwriting the output file (>>
), usetee -a
ortee --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.
Someone here has just suggested sudoing tee:
This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.
Yet another variation on the theme:
Or of course:
They have the (tiny) advantage that you don't need to remember any arguments to
sudo
orsh
/bash
A trick I figured out myself was