Introduction

Vim prevents accidental data loss by refusing to quit when there are unsaved changes, and refuses to write when the file is read-only. These errors compound when you have made changes to a read-only file:

bash
E37: No write since last change (add ! to override)
E45: 'readonly' option is set (add ! to override)
E212: Can't open file for writing

The file may be read-only due to file permissions, opened with view instead of vim, or loaded from a version control system in read-only mode.

Symptoms

  • :q fails with "No write since last change"
  • :w fails with "readonly option is set" or "Can't open file for writing"
  • :wq fails with the same errors
  • File permissions show -r--r--r-- (read-only)
  • Vim status line shows [readonly] at the bottom

Common Causes

  • File has read-only permissions on disk
  • File opened with vim -R or the view command
  • File is part of a Git repository with core.fileMode restrictions
  • File opened via a read-only file system (CD-ROM, mounted NFS with ro option)
  • User accidentally set :set readonly during editing

Step-by-Step Fix

  1. 1.Force write the file if you have write permission:
  2. 2.```vim
  3. 3.:w!
  4. 4.:q
  5. 5.`
  6. 6.The ! overrides the readonly warning. This only works if the file is actually writable.
  7. 7.Remove the readonly option and then save:
  8. 8.```vim
  9. 9.:set noreadonly
  10. 10.:w
  11. 11.:q
  12. 12.`
  13. 13.Fix file permissions from within Vim using sudo:
  14. 14.```vim
  15. 15.:w !sudo tee %
  16. 16.`
  17. 17.This writes the file as root, then you can quit with :q!.
  18. 18.Fix file permissions from the shell:
  19. 19.```bash
  20. 20.chmod u+w myfile.txt
  21. 21.# Then in Vim
  22. 22.:w
  23. 23.:q
  24. 24.`
  25. 25.Discard changes and quit if you want to abandon your edits:
  26. 26.```vim
  27. 27.:e! " Reload the file from disk, discarding changes
  28. 28.:q " Now quit works because there are no unsaved changes
  29. 29.`
  30. 30.Or force quit without saving:
  31. 31.```vim
  32. 32.:q! " Quit without saving (changes are lost)
  33. 33.`
  34. 34.Write to a different file if you cannot modify the original:
  35. 35.```vim
  36. 36.:w /tmp/myfile-edited.txt
  37. 37.:q
  38. 38.`

Prevention

  • Check file permissions before editing: ls -la filename
  • Use sudoedit instead of sudo vim for editing files that require root permissions
  • Add set readonly to your .vimrc only for specific filetypes if needed
  • Use Git's git commit -a to stage and commit changes instead of relying on file permissions
  • Set up proper file ownership so your user account can edit the files you need to
  • Use :set autoread to automatically reload files that change on disk from outside Vim
  • For configuration files in /etc/, always use sudo vim or sudoedit