What to Do If You Forgot to Use Sudo on the Command Line and Vim
Here's 2 ways to re-run a previous command. We'll also cover how to edit a root owned file in Vim without needing to run Vim with sudo.
It’s pretty easy to forget to run a command with sudo
, or especially with Vim
you might try to edit your /etc/hosts
file without sudo
but then can’t
save the file.
Rather than re-open Vim with sudo vim /etc/hosts
we’ll set things up so you
can run :W
from Vim to save the file as root regardless of how Vim was
opened. This is really nice because if you open Vim with sudo vim
it will use
your root user’s .vimrc
file which will likely be the default .vimrc
with
no plugins instead of your regular user’s customized .vimrc
.
# Demo Video
Commands
Re-running the previous command with bang bang and combining it with sudo
:
$ whoami
nick
$ !!
whoami
nick
$ sudo !!
sudo whoami
root
You can also hit CTRL + A
in most terminals to move your cursor to the
beginning of the line which lets you quickly add in sudo
to the beginning of
your command. This could be more safe than !!
if your screen is cleared and
you’re not sure what you ran last.
Setting up a custom command in Vim:
" Allow files to be saved as root when forgetting to start Vim using sudo.
command W :execute ':silent w !sudo tee % > /dev/null' | :edit!
Now you can run :W
to save your file as the root user even if you opened Vim
without sudo.
Timestamps
- 0:36 – Re-running the last command with bang bang
- 1:21 – Running the previous command with sudo bang bang
- 1:49 – Using CTRL + A to jump to the beginning of the line to add sudo
- 2:53 – Editing a root owned file in Vim but forgetting to use sudo
- 4:22 – Using a custom command to write the file out as root with regular Vim
- 5:01 – Going over the custom Vim Command
Reference Links
- The command in my .vimrc file
- https://stackoverflow.com/a/7078429 (Using
sudo tee
with Vim) - https://www.cyberciti.biz/faq/vim-vi-text-editor-save-file-without-root-permission/
Do you use sudo !! or CTRL + A more often? Let me know below.