Wednesday, 24 April 2013

Unix: Use sudo to redirect output to a location in which user doesn't have permission to write

Suppose you want to redirect output of a sudo command to  a location where you don't have write permission.

Now if you have do it in usual way , you will get permission denied error:

$ sudo echo "hello" > /etc/hello
sh: /etc/hello: Permission denied

It makes sense . Here you ran a command with sudo however file is being created with rights of current user.

This issue will be resolved as follows:

$ sudo sh -c 'echo "hello" > /etc/hello'

Here you are invoking a shell with sudo rights.

sh -c  :-  -c option provides command string to sh . It states "Read commands from the command_string operand instead of from the standard input"

No comments:

Post a Comment