Vim Save as Sudo

July 07, 2016

Have you ever had one of those days where you were trying to edit a config file and you realized that you were not sudo?

Vim-Save

Vim-Save2

Vim-Save3

Well recently I just picked up a trick from a seasoned systems admin where you can enforce your will upon the file. Instead of exiting and re-editting as sudo.

Just run this and you can see that you will be able to force save the config file as root.

:w !sudo tee %

A little about the command:

: # semi-colon to enter vim command mode
w # to write to the file
_ # space
! # vim pipe the outputs of previous command
sudo # run as sudo
_ # space
tee # tee the command
_ # space
% # Vim substitution for the current file

Written by Nick Ma 🤓, who likes learning boring complicated stuff and making it sound easy. 💻 🤔 You should follow him on Twitter

Copyright © 2019 Nick Ma.