> 文章列表 > Linux环境下VI/VIM编辑文件时无权限保存的解决方法(普通用户)

Linux环境下VI/VIM编辑文件时无权限保存的解决方法(普通用户)

在Linux环境下,如果直接使用VI/VIM命令编辑没有修改权限的文件时,保存的时候就会提示用户无法进行保存操作,一般的解决方法只能是关闭文件重新以sudo权限打开该文件编辑后再保存(前提是用户具有sudo权限)。其实,在VI/VIM模式下通过一些简单的命令,就能在不关闭当前文件的情况下达到保存文件的目的。

方法一

关于%! sudo tee % > /dev/null这条命令的说明如下

此命令是把当前文件(即%)作为stdin传给sudo tee命令来执行。

方法二

在Linux上工作的朋友很可能遇到过这样一种情况,当你用Vim编辑完一个文件时,运行:wq保存退出,突然蹦出一个错误:

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

这表明文件是只读的,按照提示,加上!强制保存::w!,结果又一个错误出现:

\"readonly-file-name\" E212: Can\'t open file for writing

文件明明存在,为何提示无法打开?这错误又代表什么呢?查看文档:help E212:

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.

原来是可能没有权限造成的。此时你才想起,这个文件需要root权限才能编辑,而当前登陆的只是普通用户,在编辑之前你忘了使用sudo来启动Vim,所以才保存失败。于是为了防止修改丢失,你只好先把它保存为另外一个临时文件temp-file-name,然后退出Vim,再运行sudo mv temp-file-name readonly-file-name覆盖原文件。

但这样操作过于繁琐。而且如果只是想暂存此文件,还需要接着修改,则希望保留Vim的工作状态,比如编辑历史,buffer状态等等,该怎么办?能不能在不退出Vim的情况下获得root权限来保存这个文件?

解决方案

答案是可以,执行这样一条命令即可:

接下来我们来分析这个命令为什么可以工作。首先查看文档:help :w,向下滚动一点可以看到:

*:w_c* *:write_c*:[range]w[rite] [++opt] !{cmd}Execute {cmd} with [range] lines as standard input(note the space in front of the \'!\').  {cmd} isexecuted like with \":!{cmd}\", any \'!\' is replaced withthe previous command |:!|.The default [range] for the \":w\" command is the whole buffer (1,$)