How to open a file in vim in read-only mode on Linux/Unix

Posted on in Categories , , , , , , , last updated January 27, 2017

I need of opening necessary files in reading (read-only) mode to avoid accidental editing of files such as /etc/resolv.conf or a large config or programming file on a production server. How do I open files in read-only mode in vim text editor on Linux or Unix-like system?

You can start vim or vi text editor in read-only mode. You will be protected from writing the files. There are various ways way to achieve write protection mode in vim.

How to open a file in readonly mode:

  1. Use view command. The syntax is: view {file-name}
  2. Use vim/vi command. The sytax is: vim -R {file-name}
  3. Modifications not allowed: The syntax is: vim -M {file-name}

Understanding options

The easiest syntax is:
$ view my-important.file
If you try to write, you will get an error as follows:

E45: 'readonly' option is set (add ! to override)

So just add !:
:w!
OR
:x!
The -R option forces read-only mode. The ‘readonly’ option will be set. You can still edit the buffer, but will be prevented from accidentally overwriting a file. If you do want to overwrite a file, add an exclamation mark to the Ex command, as in “:w!” or “:x!“.
# vim -R /etc/httpd/httpd.conf
If you made some modification and want to save it, type:
:w!
The -m option forces modifying files is disabled mode. Resets the ‘write’ option. You can still modify the buffer, but writing a file is not possible.
$ vim -m mycode.py
The -M option forces the ‘modifiable’ and ‘write’ options to be unset, so that changes are not allowed and files can not be written.
$ vim -M my-service.sh
If you try to insert or modify text, you will get an error on screen, “E21: Cannot make changes, ‘modifiable’ is off“:

Fig.01: Open a file in a tab in vim in readonly mode using -M option
Fig.01: Open a file in a tab in vim in readonly mode using -M option

A note about opening a tab in readonly mode in vim/vi

The syntax is as follows to open a new tab:
:tab sview file
OR open in a same pane:
:view file
For example, edit /etc/nginx/nginx.conf in read-only mode:
$ sudo vim +M /etc/nginx/nginx.conf
Now open a file named /etc/nginx/conf.d/cyberciti.biz.conf or /etc/nginx/conf.d/default.conf in read only mode in a new tab, use:
:tab sview /etc/nginx/conf.d/default.conf
To go to next tab type:
:tabn
To go to previous tab type:
:tabp
To list all tabs, enter:
:tabs
Sample session:

Animated gif.01: Open a file and a tab in vim in readonly mode demo
Animated gif.01: Open a file and a tab in vim in readonly mode demo

1 comment

  1. For example, edit /etc/nginx/nginx.conf in read-only mode:
    $ sudo vim +M /etc/nginx/nginx.conf

    Why is there a plus there? A typo or on purpose?

Leave a Comment