Vi Tip of the Week: Open a file in read-only mode

This is part of a series of tips on using Vi.  To see the complete series, click here.

Sometimes I want to open up a file to look at it, but not change its contents.  I could use the commands “more” or “less”, but I prefer to use vi for longer files, mostly because I’m so used to using vi.  To do so, I can use the command:

vi -R filename

where “-R” tells vi to open the file in read-only mode.  Although, I never open it with the -R option; instead I use the command:

view filename

which also opens the file in read-only mode.

Sometimes, though, I’ll be looking at the file, and realize I actually do want to make a change to it.  The hard way would be to close the file, then open it again in the regular editing mode, but instead, I can use the command mode to force a write:

:w!

If I use “ZZ” or “:w” to try to write the file, I get an error message telling me that the “readonly” option is set, but if I use the exclamation mark “:w!”, I can force vi to write the file.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.