brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: sudo tee writes to a root-owned file where a shell redirect fails

Shell
~/tips/tip-shell-sudo-tee-root-file

echo '203.0.113.10 nas.example.com' | sudo tee -a /etc/hosts >/dev/null

Append a line to a file owned by root, because sudo echo > file fails.

sudo echo '203.0.113.10 nas' >> /etc/hosts looks right and still gives Permission denied. The redirect is the part that needs root, and your own shell does it before sudo even starts.

Let a program running as root do the writing. tee writes its input to a file, so put it behind sudo:

echo '203.0.113.10 nas.example.com' | sudo tee -a /etc/hosts >/dev/null

-a appends. Leave it out and tee overwrites the file, which for /etc/hosts would be a bad surprise. The >/dev/null hides the copy that tee also prints to the screen.

For several lines, a here-document works the same way:

sudo tee /etc/sysctl.d/90-local.conf >/dev/null <<'EOF'
vm.swappiness = 10
EOF

That one creates or replaces the whole file, so it is fine for a new drop-in but not for a file with other content.

Another option is sudo sh -c 'echo ... >> /etc/hosts', but then you are juggling two layers of quotes. I find tee easier to get right.

Further reading: tee invocation (GNU coreutils)

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link