94flgg
Last Updated: February 25, 2016
·
595
· fardjad
User

How to use sudo to redirect output to a location requires root privileges for write access

You may have noticed that you get Permission denied when you execute something like this:

sudo ls > /root/ls.out

The reason is that the redirect part doesn't run under sudo. As a workaround you can do:

sudo su -c 'ls > /root/ls.out'

su -c basically switches the current user to root and runs the specified command.

Normally su asks you to enter the root password, but you can run it under sudo and enter your current user password instead.

Say Thanks
Respond

2 Responses
Add your response

5793
Aea9b3695aecb0201fba28b0fe824192

You could also use

ls | sudo tee /root/ls.out

If you want to append (>>-ish), use tee -a.

over 1 year ago ·
5794
User

@jan3000 yes, that's another way to do it but it prints the ls output on screen as well. You may also want to redirect tee output to /dev/null:
ls | sudo tee /root/ls.out > /dev/null

over 1 year ago ·
Filed Under