Sudo Redirect Output to File

One thing that’s annoying with sudo is that if you don’t own or have relevant permissions on the file you are trying to redirect to, you will get an error.

For example:

$ sudo cat /dev/null > filenotownedbyyou.log

This will fail, because even though you are using sudo, it doesn’t apply to the redirect portion of this command. So you will get “Permission denied”.

The solution is to call the entire command via bash and sudo that:

$sudo bash -c 'cat /dev/null > filenotownedbyyou.log'

This little trick can also be applied to number of situations like this.

Tags