VIM - Automatic Open Readonly File With Sudo Privilege

Overview

  • Most of time I’ll open system files with vim and after edit the system file vim says It’s readonly file.

Method 1

  • :w !sudo tee %
  • This will ask to provide sudo password and save the file.

Method 2

[mitesh@Matrix ~]$ echo "cmap w!! w !sudo tee > /dev/null %" >> ~/.vimrc
  • Save readonly file with :w!!
  • This will shortcut of Method 1.

Method 3

Create Alias

[mitesh@Matrix ~]$ echo "alias vim='~/bin/autosudo.sh'" >> ~/.bashrc

Shell Script

  • Save the below shell script as ~/bin/autosudo.sh
#!/bin/bash
FILE=$1

# Check write permission
if [ -w $FILE ]
then
  /usr/bin/vim $FILE
else
  # Use sudo if we dont have write permissions
  sudo /usr/bin/vim $FILE
fi

Make Shell Script Executable

[mitesh@Matrix ~]$ chmod a+x ~/bin/autosudo.sh && source ~/.bashrc


Newsletter

Get updated when I create new content.
Unsubscribe whenever. Never any spam.

Note

I'm Tama. I turn down every ad, affiliate, and sponsor request I get. I write free resources that help people. If you enjoy my content, please consider supporting what I do.

Support my work