This time we need to redirect the output to a file where user needs sudo privileges. The tutorial explains, how to redirect sudo output to a file in easy way. We will share some examples, which help you to redirect the output into a file where sudo command is required.

In case you are trying to redirect the output into file where root or sudo privileges is require, you will get the output – permission denied. See the below given examples.

sharad@linuxworld:~/Desktop$ echo test > /root/test
bash: /root/test: Permission denied
sharad@linuxworld:~/Desktop$ 
sharad@linuxworld:~/Desktop$ sudo echo test > /root/test
bash: /root/test: Permission denied
sharad@linuxworld:~/Desktop$

Methods to redirect output into file with sudo command

1. By using sudo sh -c

In this example we will use sudo sh -c .

Here,
sh = command interpreter (shell)
-c = Read commands from the command_string operand instead of from the standard input

Note: Notice the double quotes(“”) in command

sudo sh -c "echo 'This is new testing' > /root/test"

sudo-sh-1

2. By using sudo bash

In this example, we are using sudo bash

echo "echo 'Something new' > /root/test" | sudo bash

sudo-bash

3. By using tee command

In this examples, we will use tee command.

echo 'This is a test' |sudo tee /root/test

In case you want to append new line into file, use the argument -a with tee command.

echo 'This is a new line test' |sudo tee -a /root/test

tee-2

tee-1

Read Some More Articles

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.