A photo of Mitesh Shah

Mitesh Shah

Linux Expert | Automation Enthusiast | Security Consultant

Email Skype Github Twitter Resume Hire Me Keybase LinkedIn Stackoverflow


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




Post Navigation