Skip to content

Save file in vim with permission denied

homepage-banner

How to save file in vim when :w shows Can’t open file for writing: Permission denied.

Introduction

Vim is a popular text editor that is used by many developers and system administrators for editing configuration files and scripts. When working with Vim, you may encounter a situation where you need to save a file but do not have the necessary privileges to do so. This can happen when editing system files or files owned by another user. In this blog post, we will discuss how to save Vim without using sudo.

Saving Vim Without Sudo

To save a file in Vim without using sudo, you can use the following command:

:w !sudo tee %
:q!

This command writes the current buffer to a temporary file and then uses the tee command to write the contents of the file to the original file with root privileges.

Alternatively, you can add the following line to your .vimrc file to map a keyboard shortcut to this command:

nnoremap <leader>w :w !sudo tee % >/dev/null<CR>

This will map the leader key and w key to execute the command and save the file with root privileges.

Understanding the Command

Let’s break down the command we used to save Vim without sudo:

  • : - Enters Vim’s command mode
  • w - Writes the current buffer to a file
  • ! - Executes a shell command
  • sudo - Runs the command with root privileges
  • tee - Reads from standard input and writes to a file
  • % - Refers to the current file name
  • >/dev/null - Discards any error messages

Conclusion

In conclusion, saving Vim without sudo is a useful skill that can come in handy when editing system files or files owned by another user. By using the :w !sudo tee % command or mapping it to a keyboard shortcut, you can easily save files with root privileges. It’s important to understand how the command works to avoid any unintended consequences. Happy editing!

Feedback







Disclaimer
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback me#imzye.com, replace # with @