0%

Linux Trouble Resolver

Deliberate Practice makes Perfect!

linux中vi保存文件时的“Can’t open file for writing”

使用vi新建一个文件,编辑保存时提示“Can’t open file for writing”。

分析:

出现这个错误的原因可能有两个:
一是当前用户的权限不足;
二是此文件可能正被其他程序或用户使用。
第一项的解决方案是在使用vi命令打开文件时,前面加上sudo来临时提供管理员权限,即使用命令“sudo vi 文件名”打开编辑文件。

由此看来,sudo命令是很有用的,当我们执行某种操作系统提示诸如“operation not permitted”等权限不足信息时,我们很多时候都可以在命令前面加上sudo来解决权限不足问题。

/etc/apt/sources.list” E212: Can’t open 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:

1
2
3
4
5
sudo touch temp.txt
sudo chown root:root temp.txt
sudo chmod 775 temp.txt
whoami
el

First open the file as normal user:

1
vi temp.txt

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

1
:w !chmod 777 %

Then write the file:

1
: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.

Reference

欢迎关注我的其它发布渠道