How to append text to a file when using sudo command on Linux or Unix

Posted on in Categories , , last updated May 30, 2017

I am trying to add entry to /etc/hosts file using ‘sudo echo '192.168.1.254 router' >> /etc/hosts‘ but getting an error that read as, -bash: /etc/hosts: Permission denied. How do I insert or append text to a file when running sudo command on Linux or Unix-like system?

There are various ways to append a text or data to a file when using sudo command on Linux or Unix. You can use the tee command that copies input to standard output. Another option is to pass shell itself to the sudo command.
Fig.01: How to append/insert text into a file using sudo on Linux or Unix-like system?
Fig.01: How to append/insert text into a file using sudo on Linux or Unix-like system?

Let us see both methods.

Method 1: Use tee command

The syntax is:
echo 'text' | sudo tee -a /path/to/file
echo '192.168.1.254 router' | sudo tee -a /etc/hosts

Sample outputs:

Password:
192.168.1.254   router

This solution is simple and you avoided running bash/sh shell with root privileges. Only append or write part needed root permission.

Method 2: Use bash/sh shell

The syntax is:
sudo sh -c 'echo text >> /path/to/file'
sudo -- sh -c "echo 'text foo bar' >> /path/to/file"
sudo -- bash -c 'echo data >> /path/to/file'
sudo bash -c 'echo data text >> /path/to/file'

For example:
sudo sh -c 'echo "192.168.1.254 router" >> /etc/hosts'
You are running bash/sh shell with root privileges and redirection took place in that shell session. However, quoting complex command can be problem. Hence, tee method recommended to all.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

5 comment

Leave a Comment