Using sudo and tee together is a "power move" in Linux. It's the standard way to write text to files that your normal user doesn't have permission to edit (like those in /etc).
Here are three practical tasks where this combination is extremely useful:
1. Appending to a System File
If you want to add a line to a protected file (like adding a new IP to /etc/hosts) without overwriting the whole file, use the -a (append) flag with tee.
echo "192.168.1.50 myserver.local" | sudo tee -a /etc/hosts
Why this is better than sudo echo ... >> /etc/hosts: Redirection (>>) is handled by the shell, not the command. Since your shell isn't running as root, >> would fail even if you used sudo echo. tee solves this because it runs as root.
2. Creating a Configuration File with Heredoc
You can use a Heredoc with sudo tee to create a multi-line configuration file in one go. This is very common when setting up web servers or repository lists.
sudo tee /etc/apt/sources.list.d/example.list << EOF
# Example Repository
deb http://archive.ubuntu.com/ubuntu focal main
deb-src http://archive.ubuntu.com/ubuntu focal main
EOF
3. Writing to Multiple Files Simultaneously
The tee command is named after a T-shaped pipe. It splits the input—sending it to the screen AND to one or more files.
echo "Port 2222" | sudo tee config_backup.conf /etc/ssh/ssh_config.d/custom.conf
This saves the same text to both a local backup and a system directory at the same time.
Summary Table
| Goal | Command |
|---|---|
| Write/Overwrite | `echo "text" |
| Append (Add to end) | `echo "text" |
| Multi-line Root File | sudo tee /path/file << EOF ... EOF |
| Discard Screen Output | `echo "text" |
Try it out: You can try creating a test file in /etc (just don't change existing ones!) to see it in action:
echo "Labby was here" | sudo tee /etc/labby_test.txt