linux - [Solved-5 Solutions] How to use sudo to redirect output to a location in Linux ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
To find myself quite often needing to redirect output to a location but don't normally have write access to.
The trouble is, the following example doesn't work:
You just receive the response:
How can you get this to work?
Linux - Solution 1:
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.
- 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 (>>), use tee -a or tee --append (the last one is specific to GNU coreutils).
Linux - Solution 2:
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.
Linux - Solution 3:
Linux - Solution 4:
Or of course:
Linux - Solution 5:
Make sudo run a shell, like this: