Learn how to open file in read only mode under vi or vim editor. Opening read only prevents any accidental edits in file and maintain file integrity.
“vi editor” is sysadmin’s and programmer’s daily text editor in Linux Unix systems. Opening a file to view its content can be achieved by many commands like
less etc. But many prefer to open a file in vi editor to view. Especially when file is long and one needs to search particular terms in it. Vi editor makes it easy to search content, line numbering while viewing files.
One of the disadvantage is you are prone to accidentally alter file content and end up in saving it in file. This is threat to file integrity and hence needs to be avoided. Option is to view files in vi editor carefully or open them in read only mode!
Lets see different ways to view file in read only mode under vi :
1. Use of view command
One of the widely used way to view file in vi editor. Simple open file with view command. It will open in vi editor and any attempt to save/alter data will result in failure, securing your file from accidental edits.
# view test.txt This is test file Test text File ends here. ~ ~ ~ ~ ~ "test.txt" [readonly] 3L, 44C
You can see above it shows
readonly at bottom and open file in vi editor. If you get into
INSERT mode to edit any content of file you will see below warning.
W10: Warning: Changing a readonly file
If you try to save edited content then you will see below warning
E45: 'readonly' option is set (add ! to override)
So this is 2 level warnings before you could actually save file using override option
w!. There is no way you could *accidentally* ignores two warnings and make accidental edit in file!
2. vi or vim command with -R option
Another way is to open file in vi editor with
-R option. It functions the same way as above and also shows same double layered warning messages when you enter INSERT mode and try to save file. This option still let you save the edits made in buffer by using override
You can open file using
vi -R filename
3. vi modifications not allowed mode
Modification not allowed mode can be called using
-M option. From man page, The ’modifiable’ and ’write’ options will be unset, so that changes are not allowed and files can not be written.
Unlike above two options, this mode wont let you edit file at all. It will show below error at bottom when you enter INSERT mode.
E21: Cannot make changes, 'modifiable' is off
So you wont be able to type in anything even you try INSERT mode. If you try to save file with
:w then it will show you below error :
E142: File not written: Writing is disabled by 'write' option
This makes it most secure way to open file in read only mode under vi to avoid accidental content alteration!
Let us know which way you use most in your daily operations in comments. Happy viewing! 🙂