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

Breaking

Post Top Ad

Post Top Ad

Thursday, November 30, 2017

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

Iam 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.

No comments:

Post a Comment

Post Top Ad