linux保存文档失败权限不够,使用vim保存权限不够的文件

当在Linux中使用vim编辑器遇到权限不足无法保存文件时,可以采用两种方法解决:1) 使用`:w !sudo tee %`,通过tee命令将内容追加到文件;2) 使用`:w !sudo cat > %`,结合shell的重定向功能。这两种方法都利用了vim执行外部命令的特性,实现了在普通用户权限下保存需要root权限的文件。
摘要由CSDN通过智能技术生成

问题描述

今天在根目录下,使用vim编辑器编写了一段程序,但是在保存的时候被提示:E505:“file” is read-only(add ! to override )

强制写入呢?结果是E212: Can't open file for writing.

我们使用vim自带的帮助文档,可以看到

Cannot open "{filename}" for writing

Can't open file for writing

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权限造成的。

解决方法一(tee)

这时我们需要输入这样一段命令

:w !sudo tee %

解释一下这行命令什么意思?

w的意思

通过在vim下查看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} is

executed like with ":!{cmd}", any '!' is replaced with

the previous command |:!|.

The default [range] for the ":w" command is the whole buffer (1,$).  If you

write the whole buffer, it is no longer considered changed.  When you

write it to a different file with ":w somefile" it depends on the "+" flag in

'cpoptions'.  When included, the write command will reset the 'modified' flag,

even though the buffer itself may still be different from its file.

接下来是一个叹号!,它表示其后面部分是外部命令,即sudo t

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值