Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:wq! command in vim

Tags:

vim

root

Recently, I read here about the :wq! command in vim. I don't understand how it can force-write a file without write permissions. This way, theoretically, one would be able to edit root files without permission. Shouldn't it be disallowed? Or does it write into a new file? I saw a similar question, but that is about motions and is very different.

P.S. I haven't tried the command for fear of messing up system files.

like image 800
Zargles Avatar asked Sep 10 '18 03:09

Zargles


People also ask

What is command WQ?

Press Esc to enter Command mode, and then type :wq to write and quit the file. The other, quicker option is to use the keyboard shortcut ZZ to write and quit. In Vi, write means save, and quit means exit.

How do I save A document in vi?

To save a file in Vim / vi, press Esc key, type :w and hit Enter key.


3 Answers

If you don't have permission to the file (e.g. you don't own the file), then it will not force the write. If you do have permission to the file, but it is a read-only file, then you can force-write it. It's as if you first change the file mode to writable, write your changes, and then change the file mode back to read-only.

like image 191
yty Avatar answered Oct 01 '22 15:10

yty


Do not be afraid, vim cannot grant you more rights than the OS would give you anyway. w! is useful to override read-only mode if you happened to open a file with the vim -R command or if you had made the file read-only before opening it with vim for yourself.

like image 25
tif Avatar answered Oct 01 '22 15:10

tif


You should consider the directory permissions guys! I mean the directory which file is in it. As you should know, if you have write permission on a directory, you could remove all of the files in it, and create new files even with same names (like overwriting)!

When you modify read-only file with vi and you insert wq! to write changes, there would be two situations:

  1. You have write(w) permission on the directory
    • The main file would be deleted and new file with the same name would be written.
  2. You don't have write(w) permission on the directory
    • Nothing happens! You could not write or modify the file, and you should quit: q!.

So write permission on directory is important for read-only files!

like image 22
Unique_boy96 Avatar answered Oct 01 '22 15:10

Unique_boy96