Last Updated: February 25, 2016
· fardjad

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.

2 Responses
Add your response


You could also use

ls | sudo tee /root/ls.out

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

over 1 year ago ·

@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 ·