Forgetting to run vim with sudo
2026-01-02
Ever make edits to a file with vim, only to realize you forgot to open it with sudo? Yeah, me too.
For eons, I'd close the file, reopen with sudo, and re-edit the file. Obviously, this sucks, so I looked up a better solution, and now I share it with you:
:w !sudo tee %
:w accepts arguments, such as a filename (:w file2.txt), but anything prefixed with an explanation point is interpreted as a shell command with the file contents passed to stdin. sudo tee will overwrite the file (vim will substitute % with the filename) with the contents from stdin.
Credit to Nathan Long on stackoverflow for a much better explanation.