Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

What to Do If You Forgot to Use Sudo on the Command Line and Vim

blog/cards/what-to-do-if-forgot-to-use-sudo-on-the-command-line-and-vim.jpg

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.

Quick Jump: Demo Video

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

Do you use sudo !! or CTRL + A more often? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per month (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments