Vim ошибка e212

«I am trying to edit sources.list using vi editor but getting the following error while saving the file:

/etc/apt/sources.list» E212: Can’t open file for writing» — from Stack Overflow

can't open file for writing in Vim

If you’re a Linux user using Vim, you may have encountered the following error while trying to write to a file: E212 can’t open file for writing. This article will show you three ways to fix this error. All of these methods work in Ubuntu and other Debian-based distributions. Let’s get started!

Workable Solutions Step-by-step Troubleshooting
1. Check File Permissions Edit the «sources.list» file using a non-root-user with the following command…Full steps
2. Check the File Lock Find the file with this command: lsattr /home/admin/$filename…Full steps
3. Fix Read-only File System Check the disk space with this command. $ df -h. Then, make space by deleting…Full steps

Reasons — E212 Can’t Open File for Writing

This problem can be caused by many things, from a permissions issue to low disk space. In this part, we’ll analyze the reasons. Let’s get started!

When using the vi command to modify the content of a Linux file, it is found that it cannot be saved. Every time you finish writing, you can use the «:q!» command to exit normally. However, when you use the «:wq!» command to save the file and exit, these error messages prompt:

  • Vim Can’t Save File (E212)
  • Vim can’t open file for writing
  • Root user can’t open file for writing
  • /etc/apt/sources.list» E212: Can’t open file for writing
  • E212: Can’t open file for writing. Press ENTER or type command to continue

You receive this error for two main reasons:

  • The current user has insufficient permissions.
  • This file may be in use by other programs or users.

Solutions — 3 Ways to Fix Can’t Open File for Writing in Vim

E212: can’t open file for writing is an error that can occur when trying to save a file in Vim. There are a few different ways to fix this error, depending on the cause. 

Method 1. Validate User and Check File Permissions

The general cause of the error is the permission issue. The solution is to add sudo in front of the file to temporarily provide administrator privileges when using the vi command to open the file. For example, use the command «sudo vi hosts» to open and edit the file.

Step 1. Edit the «sources.list» file using a non-root-user with the following command.

$ vim /etc/apt/sources.list

Step 2. Get «/etc/apt/sources.list» E212: Can’t open file for writing» error.

Step 3. Run sudo permissions to fix the error.

$ sudo vim /etc/apt/sources.list

Validate user and check file permissions to fix can't open file for writing in Vim

Method 2. Check If the File Is Locked to Fix Can’t Open File for Writing

If you are a root or sudo user, but you still can’t open the file for writing. Then, you can try to exit the file and check if the «I» command locks it.

check the lock to fix can't open file for writing in Vim

Step 1. Find the file with this command:

lsattr /home/admin/$filename

Step 2. Check the I lock.

If there is an «I» displayed, the file is locked. You can execute this command to unlock your files.

chattr -i $filename

After this, execute q! to exit the file. When viewing the file again, it is found that the content has been changed and saved.

Method 3. Check for Read-only File System or Capacity Issue

You still face this error if you have permission and use the sudo command. Then, you need to check for a read-only file system or capacity issue.

Step 1. Check the disk space with this command.

$ df -h

check read-only file system to fix can't open file for writing in Vim

Step 2. Then, make space by deleting or removing unnecessary files using the rm command.

Step 3. Run mount command to check for your device. It must be mounted as read-write (rw) not read-only (ro).

$ mount

Step 4. Fix the file system errors and re-mount it to a read-write file system.

$ sudo mount -o remount,rw /partition/identifier /mount/point

or

$ sudo mount -o remount,rw /

Then, you have resolved the «E212: Vim can’t open file for writing» error. You can watch this video to get help if you still have problems.

  • 0:17 fix can’t open file for writing while using Vim
  • 0:50 make sure the path
  • 2:57 check the file permission

How to Recover Lost Linux Files with Software

What if you lost data after fixing the «E212: Vim can’t open file for writing» error? Don’t worry. EaseUS Data Recovery Wizard is a helpful tool for recovering lost data on Linux systems. It has a simple interface that makes it easy to use, even for those who need to become more familiar with data recovery programs.

  • EaseUS Data Recovery Wizard can recover deleted files from any storage device, including hard drives, USB flash drives, and memory cards.
  • It also supports various file types, such as photos, videos, documents, and emails.
  • Best of all, EaseUS Data Recovery Wizard is very easy to use. This makes it an excellent choice for anyone who needs to recover lost data on a Linux system.

Download this software and find files in Linux.

Step 1. Select a drive and start scanning

Launch EaseUS Data Recovery Wizard and hover over the partition where you lost data. This could be an internal hard disk, external disk, USB, or SD card. Then, click «Scan».

select a location to scan

Step 2. Check and preview scanned files

Use the file format filter on the left or upper right corner to narrow the scan results until you find the files you need. Then, you can click the «Preview» button or double-click a file to preview its content, if you’d like. 

Choose files to recover

Step 3. Recover lost data to a secure location

Click the checkbox next to the file and click «Recover» to restore the lost data to a secure place. We recommend that you do not store the recovered data on the disk where you lost it earlier.

Recover lost data

Conclusion 

Follow the solutions above to fix the «can’t open file for writing» error in Vim without losing data. If you have any questions or need help, feel free to reach out and contact us. We’re here to help!

Can’t Open File for Writing FAQs

Read the questions and answers below to get additional help.

1. What to do if you are faced with the action can’t be completed error?

To fix the action can’t be completed because the file is open:

  • Run File Locksmith
  • Stop Processes with Task Manager
  • Empty the Recycle Bin and Restart
  • Restart Windows Explorer
  • Delete Temp Files

2. How do you fix cannot open file for writing in Vim?

You can fix the can’t open file for writing in three ways:

  • Check File Permissions
  • Check If the File Is Locked
  • Check for Read-only Memory

3. How to exit Vim in the terminal without saving?

To exit Vim without saving changes:

  • Switch to command mode by pressing the Esc key.
  • Press : (colon) to open the prompt bar in the bottom left corner of the window.
  • Type q! after the colon and hit Enter to exit without saving the changes.

4. What is Vim used for?

Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems.

Vim — это текстовый редактор, используемый в операционных системах Linux, который помогает создавать и обновлять различные текстовые файлы с разными расширениями. Иногда, когда вы пытаетесь создать файлы с помощью утилиты Vim, вы получали ошибку: “Vim can’t open file for writing”. Причин этой ошибки может быть несколько.

Предпосылки:

На вашем компьютере должен быть установлен и настроен дистрибутив Linux. В нашем случае у нас есть дистрибутив Linux Ubuntu 20.04. С другой стороны, у вас должны быть права sudo для использования системы Linux и утилиты Vim.

Установка Vim:

В самом начале вы должны убедиться, что в вашем дистрибутиве Linux установлена ​​утилита Vim. Для этого мы сначала проверим это в нашей системе. Следовательно, вы должны открыть терминал командной строки из панели действий на рабочем столе Linux. После этого выполните приведенную ниже команду Vim, чтобы получить информацию о Vim. Как показано на изображении, в нашей Ubuntu 20.04 не установлена ​​утилита Vim. Он также предлагает некоторые инструкции по установке Vim в системе. Используйте один из них для установки Vim.

$ vim

Теперь наша очередь установить Vim в нашей системе Linux. Итак, для этого мы должны использовать команду sudo apt. Попробуйте выполнить команду ниже, чтобы установить его в вашей системе. Для инициализации процесса установки потребуется пароль вашей учетной записи root. Введите свой пароль sudo и нажмите кнопку «Enter», чтобы продолжить. Вы увидите, что он начнет установку и загрузку утилиты Vim вместе с другими пакетами.

$ sudo apt install vim

Во время установки он будет приостановлен, и появится вопрос. Система предложит вопрос для подтверждения действия по установке, в котором говорится: “Do you want to continue? [Y/n] “. Если вы хотите продолжить процесс установки Vim, вам нужно нажать «y» и нажать Enter, в противном случае нажмите «n» и нажмите кнопку «Enter». Итак, мы нажали «Y» и нажали клавишу Enter, чтобы продолжить установку редактора Vim в Ubuntu 20.04. Это запустит правильную установку редактора Vim. Вам нужно подождать некоторое время, пока он не завершит свой процесс.

После установки Vim вы можете проверить информацию о нем, используя ту же команду, что и ниже.

$ vim

Если ваша система Linux успешно откроет окно, показанное ниже, как показано на прикрепленном снимке, вы можете использовать редактор Vim.

Ошибка устранения неполадок. Vim не может открыть файл для записи

Получите ошибку:

Теперь мы создадим файл с помощью команды Vim в командной оболочке. Мы создадим этот файл в любом из каталогов. Итак, попробуйте следующую команду Vim, чтобы создать файл «smtpd.conf» в каталоге, указанном ниже.

$ vim /usr/lib64/sas12/smtpd.conf

Откроется окно, показанное ниже, в котором путь и имя файла указаны в нижней части нижнего заголовка. Пора записать содержимое этого файла по заданному пути.

Чтобы записать содержимое файла и выйти из редактора Vim, попробуйте следующую команду «wq» со знаком двоеточия «:», затем нажмите кнопку Enter, чтобы запустить эту команду.

Сразу после того, как вы нажмете кнопку «Enter», вы получите сообщение об ошибке: “E212: Can’t open file for writing”, как показано на изображении ниже. Для продолжения нажмите кнопку «Enter». Ошибка устранения неполадок. Vim не может открыть файл для записи

Чтобы проверить причину этой ошибки, нам нужно написать еще одну инструкцию в редакторе Vim. Попробуйте выполнить следующую команду sudo в редакторе Vim, начиная с ключевого слова «:w», заканчивая ключевым словом «tee» и знаком процента. Нажмите клавишу «Enter», чтобы увидеть причину ошибки.

:w ! sudo tee %

Для записи содержимого файла и сохранения файла по указанному пути требуется пароль вашей учетной записи sudo. Введите свой корневой пароль и нажмите кнопку «Enter». Вывод показывает, что в вашей системе Linux нет такого файла или каталога. Это означает, что мы указываем причину этой ошибки. Снова нажмите клавишу «Enter», чтобы продолжить работу с Vim. Напишите приведенную ниже команду выхода и нажмите клавишу «Enter», чтобы вернуться в оболочку терминала.

Мы узнали о причине ошибки, которая заключается в том, что указанный путь не был фактически создан. Вы также можете проверить путь в командной строке с помощью команды ls. Вывод показывает, что такой каталог не создается.

$ ls /usr/lib64/sas12

Устранить ошибку:

Во-первых, мы должны создать путь или каталог в оболочке командной строки. Чтобы создать каталог, указанный в указанном выше пути, мы должны использовать команду mkdir вместе с флагом «-p». Если вы используете команду mkdir без ключевого слова «sudo», это может быть вызвано исключением «Permission denied».

$ mkdir –p /usr/lib64/sas12

Давайте попробуем эту команду с ключевым словом «sudo», и вы увидите, что она работает нормально.

$ sudo mkdir –p /usr/lib64/sas12

Снова напишите команду Vim, а затем укажите путь к файлу, чтобы проверить изменения. Откроется редактор Vim.

$ vim /usr/lib64/sas12/smtpd.conf

Когда вы напишете приведенную ниже команду sudo, для продолжения может потребоваться пароль вашей учетной записи sudo. Вы можете увидеть, что после ввода пароля и нажатия кнопки «Enter» будет выдано предупреждение. Вы должны нажать клавишу «L», а затем кнопку «Enter», чтобы загрузить этот файл в указанную папку.

:w !sudo tee %

Он загрузит файл и предоставит ему права только для чтения. Нажмите клавишу Enter.

Теперь, когда вы вводите команду «wq», она будет работать нормально.

Заключение:

Мы сделали решение ошибки: “Vim can’t open file for writing” в мгновение ока. Надеюсь, вы сможете решить эту ошибку с удобством.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

That happens to me all the time, I open a root file for writing:

Instead of losing all your changes and re-opening with sudo. See this demo of how to save those changes:

One time Setup demo to create a root owned read only file for a lower user:

sudo touch temp.txt
sudo chown root:root temp.txt
sudo chmod 775 temp.txt
whoami
el

First open the file as normal user:

vi temp.txt

Then make some changes to the file, it warns you its read only. Use this command.

:w !chmod 777 %

Then write the file:

:wq!

The permissions are expanded, and the file is saved. You need the exclamation point because you are editing a root file as a lesser user.

Explanation of what that command does:

The :w means write the file. The bang means start interpreting as shell. chmod means change permissions, 777 means full permissions everywhere. The percent means the current file name.

It applies the change. And it ask if you want to re-load. Press «O» for «Ok». Don’t reload or you’ll lose your changes.

Vim can’t open file for writing error is one of the most common and frequent errors you will encounter, if you use Linux and vim editor. Whether you are a novice or Pro Linux user, “E212” is the error code, you don’t like seeing. Most of the time, this error occurs due to insufficient rights or a directory path or file that doesn’t exist, which you are trying to edit. In this post, I will let you know all the reasons and solutions to fix the “Vim can’t open file for writing” error.

When you use Linux, you can get the below-mentioned error, while you try to edit a file –

  • /etc/apt/sources.list” E212: Can’t open file for writing
  • Vim Can’t Save File (E212)
  • Vim can’t open file for writing
  • Root user can’t open file for writing
  • Error in editing vimrc
  • E212: cant open file for writing ec2

Possible causes of the above-mentioned issues –

  • You don’t have access or you are trying to edit a file, which is owned by root user
  • Path of the file, you are trying to edit doesn’t exist (non existing file, non existing directory)
  • Trying to write a network drive and you don’t have access or partial access
  • Trying to edit a read only file system
  • Not enough space exists in your current partition or drive.

Let’s deep dive and fix errors and it’s causes one by one.

Install vim editor in Ubuntu, if not there already

If you get the error: “Command ‘vim’ not found, but can be installed with:” it means you don’t have vim (visual improved) editor installed. Run the following command to install the package in Ubuntu.

$ sudo apt install vim

Install vim in ubuntu using apt install vim command

Solution-1 Check the directory or path of file, create it if it doesn’t exist

First thing first, if you are getting vim can’t open file for writing error, check the path and directory of the file. Let’s understand it from an example.

I am trying to run a command “vim /home/tmp/sample.txt” and getting this error “/home/tmp/sample.txt” E212: can’t open file for writing” while saving it as shown in the image.

vim can't open file for writing

In this scenario, the “tmp” directory inside /home doesn’t exist. So if you will try to either create a new or edit the existing “sample.txt” file. This will not work and you will get errors.

In my case, I need to create the directory tmp inside the /home first to get rid of this "E21: can't open file for writing" error. This may happen in your case also. You may need to create the required directory or maybe you just need to correct the required path :-).

If you want to create a directory without closing the vim editor prompt because you have already edited the file and you don’t want to lose changes. Then follow these steps-

  • Press “ESC” on your keyboard.
  • Type “!sudo mkdirpath of directory that need to be created“. For example, in my case i need to create “tmp” directory inside /home.

E.g.

:!sudo mkdir /home/tmp/

create directory using vim editor

As soon as you will run this command and press enter, It may ask you to give your sudo credentials, and your required directory will get created as shown in the image.

validate directory after creating it from Vim editor

You can edit, save and exit your file now with the “:wq” command without any issue.

How to get the reason of error “E21: can’t open file for writing” using vim help

To find out the reason for the error, follow these steps in the vim editor prompt, where you are getting an error.

  • Press “esc” key on your keyboard
  • Then type :h e212 as shown in image “:h -“ represents help and e212 error. Same way you can check for any error, you encountered in vim editor

how to get error help e212 in vim

  • Press enter and you will get the error code and its reason. For example, in my case it is showing the follow –
For some reason the file you are writing to cannot be created or overwritten.
The reason could be that you do not have permission to write in the directory
or the file name is not valid.

/etc/apt/sources.list E212: Can't open file for writing

Press the “ESC” key and then type “:q!” to exit from help.

How to fix etc/apt/sources.list” E212: Can’t open file for writing

If you use Linux, many times in your lifetime. You would have edited the sources.list file and I am sure, you would have encountered an E212 error. Follow solution-2 step by step to fix this issue.

Solution-2 Validate User or file permissions

If you are trying to edit a file and you have given the correct path but still you are getting “can’t open file for writing error“, then you are a victim of permission issues.

If you are logged in with a non-root user, make sure you start with the sudo command, if you are trying to edit a system file or file owned by root.

Let me show you an example, try editing /etc/apt/sources.list with a non-root user and you will understand, what I am trying to prove here.

If you will see the below image, the “sources.list” file is owned by root, so if you will try to edit it using a non-root-user with the following command

$ vim /etc/apt/sources.list

check ther permission of file first, if you are not able to edit the file in vim

You will get “/etc/apt/sources.list” E212: Can’t open file for writing” error.

To fix it, you must edit this file using sudo permissions. run the following command to edit this file successfully.

$ sudo vim /etc/apt/sources.list

How to fix even if “Root user can’t open file for writing”

If you are a root or sudo user, Also you have given the correct path to directory or file but still, you are not able to open the file for writing. Then you are trying to edit a read-only file system or your disk space is full, which doesn’t allow editing and saving a file.

Solution3- Check for Read-only file system or Capacity issue

Use the “df” command to check the partition or disk space usage. If you see “disk” or “partition” available space is showing “0” bytes except for “/dev/loop”.

Then make space by deleting or removing unnecessary files using the rm command. It will fix your “vim can’t open file for writing” issue.

$ df -h

check for capacity issue

If you have enough space, then make sure your file system is not mounted as read-only. Run the “mount” command and check for your device, it must be mounted as read-write (rw) not read-only (ro).

For example, /dev/sda5, which is my root (/) partition, mounted as rw.

$ mount

check for file system is read only or read write in ubuntu

If it is showing mounted as read-only in your case, then remount it as rw. If it’s happening due to file system errors, then fix the file system errors and re-mount it to a read-write file system.

$ sudo mount -o remount,rw /partition/identifier /mount/point

or

$ sudo mount -o remount,rw /

You will be able to edit your file, once your file system will be rw and your “vim can’t open file for writing” will vanish.

Video tutorial

Conclusion

I am hopeful, that one of the 3 solutions shared in this post will fix your “E212: Vim can’t open file for writing” error. If you are still facing issues, You can let me know, via your comments. I will try to help you to the best of my knowledge.

Vim is a popular text editor that has been around for a few decades. It’s commonly included as a standard option to edit text files with most Linux distributions and Mac OS X. Vim is incredibly powerful and flexible – for example, it can work with several files at once through tabs, or easily run automated tasks from inside itself. A huge range of other text editors are introduced from time to time, but Vim has remained a popular option for those wanting more customization and control over their workflow.

One of the most popular error messages that confuses Linux beginners is the “E212: Can’t open file for writing” in vim. The full error log can look like below :

"path/to/example.txt" E212: Can't open file for writing
Press ENTER or type command to continueCode language: PHP (php)

The cause of this error, according to Vim manual, is :

For some reason the file you are writing to cannot be created or overwritten.
The reason could be that you do not have permission to write in the directory
or the file name is not valid.

In this article, we will show you a few ways to fix the “E212: Can’t open file for writing” while working with Vim.

Install vim in Ubuntu

If you see the error message “Command ‘vim’ not found”, it means you don’t have the vim editor installed.

Install vim in Ubuntu

You can install it by running the following command in Ubuntu:

sudo apt-get install vimCode language: JavaScript (javascript)

Check the file path for its existence

The first thing you need to do is checking the directory or the file path in order to be sure that it does exist. If it doesn’t or one of its parent directory doesn’t, trying to open it with Vim will definitely raise “E212: Can’t open file for writing” error.

In the example below, I’m trying to edit a file in /home/tmp/example.txt but getting “E212: can’t open file for writing” every time I try to save it, as shown in the image below.

In this scenario, you will not be able to create or edit the “example.txt” file inside the /home/tmp directory, as it does not exist.

Now you have two options. You can exit vim , run mkdir tmp to manually create the directory and then start creating the file all over again. Or you can direcly run a command without leaving vim by following the instructions below :

  • Press ESC key to get out of “Please ENTER or type command to continue” prompt.
  • Type !sudo mkdir /home/tmp” followed by Enter key in order to make a new tmp directory inside home. The exclamation mark prefix tells vim to send this command to the system instead of recognizing it as an internal one. Remember to replace /home/tmp/ with your path.
  • Vim now ask for your root password, input it like you usually do when running sudo.

Make sure you have write permission

We’ve seen many users “E212: Can’t open file for writing” error when trying to edit sources.list file. This is because the file you’re trying to edit is placed in a directory where you don’t have the write permission, or have no permission at all. Run the following command to be really sure that this is the case and the destination file is owned by another user :

ls /etc/apt/

Make sure you have write permission

If you’re logged in as a non root account, prefix the command with sudo usually get rid of the problem.

sudo vim /etc/apt/sources.listCode language: Access log (accesslog)

Check for Read-only filesystem or full disk space

If none of the above solution worked for you, the cause might has something to do with the filesystem or storage capacity.

While being a possible reason, it’s unlikely the storage capacity is the real reason. If it does, you may have seen countless system notifications before you can actually editing anything. But in order to be really sure, run df -h in a terminal and look in the output for 100% use on any mounted path.

The last thing that causes E212 error in Vim is a read-only filesystem. In order to verify if this is the case, run mount command in a terminal. You should find that your device is mounted with rw permission, and not read-only (ro).

If your device is mounted as read-only, run the following command to re-mount it with the correct permission. Remember to replace /mount/point and /partition/identifier with the proper value.

sudo mount -o remount,rw /partition/identifier /mount/point
# or
sudo mount -o remount,rw /Code language: Shell Session (shell)

Once the command completes its job, you should be able to edit your files again without encountering “E212: Can’t open file for writing”.

We hope that the information above is useful to you. If you’re interested in a modern source code editor, check out VSCode as well as our guides on how to enable/disable word wrap in VSCode, How to use LaTeX in VSCode or how to automatically indent your code in Visual Studio Code.

Понравилась статья? Поделить с друзьями:
  • Vestel ошибка e07
  • Vimeworld критическая ошибка рабочий путь лаунчера неверен
  • Vim ошибка e37
  • Vestel wms 840 ts ошибки
  • Vestel wms 4010 ts ошибки