Learn how to open the file in the read-only mode under vi or vim editor. Opening it as read-only prevents any accidental edits in the 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 editors to view. Especially when the 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 disadvantages is you are prone to accidentally alter file content and end up saving it in the file. This is a threat to file integrity and hence needs to be avoided. The option is to view files in vi editors 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 ways to view files in vi editors. Simple open file with view command. It will open in vi editors 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 the bottom and open file in vi editors. If you get into
INSERT mode to edit any content of the 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 the file using override option
w!. There is no way you could *accidentally* ignores two warnings and make accidental edits in the file!
2. vi or vim command with -R option
Another way is to open the file in vi editors with
-R option. It functions the same way as above and also shows the same double-layered warning messages when you enter INSERT mode and try to save the file. This option still lets you save the edits made in the 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 the man page, The ’modifiable’ and ’write’ options will be unset, so that changes are not allowed and files can not be written.
Unlike the above two options, this mode won’t let you edit files at all. It will show below error at the bottom when you enter INSERT mode.
E21: Cannot make changes, 'modifiable' is off
So you won’t be able to type in anything even you try INSERT mode. If you try to save the file with
:w then it will show you below error :
E142: File not written: Writing is disabled by 'write' option
This makes it the most secure way to open files in the 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! 🙂
Share Your Comments & Feedback: