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
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
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
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]$
sudo tee (if you have to escape a lot when using the
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
tee -a or
tee --append (the last one is specific to GNU coreutils).