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

sudo echo '192.168.1.254 router' >> /etc/hosts

-bash: /etc/hosts: Permission denied

ADVERTISEMENTS



Method 1: Use tee command

I am trying to add entry to /etc/hosts file using ‘‘ but getting an error that read as,. 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 opies input to standard output. Another option is to pass shell itself to the sudo command. This page includes examples of appending to a privileged file with the help of sudo and tee commands.Let us see both methods.

The tee command read from standard input (such as keyboard) and write to standard output (such as screen) and files. 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.

Bash: append to file with sudo and tee

Want to append text to more than one file while using sudo? Try:

echo 'data' | sudo tee -a file1 file2 fil3

Verify that you just appended to a file as sudo with cat command:

cat file1

cat file2

We can append to a file with sudo:

cat my_file.txt | sudo tee -a existing_file.txt > /dev/null

It is a good idea to redirect tee output to /dev/null when appending text. In other words, use >/dev/null when you don’t want tee command to write to the standard output such as screen.

Understanding tee command options

-a OR --append : Append to the given FILEs, do not overwrite -i OR --ignore-interrupts : Ignore interrupt signals -p : Diagnose errors writing to non pipes

See tee command man page by typing the following man command man tee

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.

Conclusion

As we learned that there are multiple ways to append text to a file using the sudo command.

Category List of Unix and Linux commands File Management cat Network Utilities dig • host • ip • nmap Package Manager apk • apt Processes Management bg • chroot • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time Searching grep • whereis • which User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w