以非 root 身份编辑后将文件另存为 root
好吧,这种情况经常发生在我身上。必须有更好的解决方案。假设您执行了 vim /etc/somefile.conf
,然后执行了 i
,但意识到您不是 sudo
并且无法写入。因此,我通过执行 :q
然后 sudo !!
丢失了我的更改,并再次进行更改。有更好的方法吗?
Ok so this happens to me all the time. There has to be a better solution. Let's say you do vim /etc/somefile.conf
and then you do i
but realize you are not sudo
and you can't write. So then I lose my changes by doing :q
then sudo !!
and make my changes again. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
尝试
w !
获取整个文件并将其通过管道传输到 shell 命令中。 shell 命令是 sudo tee,它以超级用户身份运行 tee。%
替换为当前文件名。名称中包含空格或任何其他特殊字符的文件需要引号。Try
The
w !
takes the entire file and pipes it into a shell command. The shell command issudo tee
which runstee
as superuser.%
is replaced with the current file name. Quotes needed for files that have either spaces or any other special characters in their names.根据更改的程度,使用不同的名称保存 (
:w
) 文件,然后使用sudo
和cat 覆盖原始文件的内容:
sudo sh -c 'catchanged> file'
请注意,
cp
和mv
都将替换原始文件,并且其属性(所有权、权限、ACL)将丢失。 不要使用它们,除非您知道如何在事后修复权限。Depending on the extent of your changes, it might be faster to save (
:w
) your file with a different name, and then usesudo
andcat
to overwrite the content of the original file:sudo sh -c 'cat changed > file'
Note that both
cp
andmv
will replace the original file and its attributes (ownership, permissions, ACLs) will be lost. Do not use them unless you know how to fix the permissions afterwards.将文件保存在其他位置(例如您的主文件夹),然后使用
sudo mv
覆盖原始文件?Save the file elsewhere (like your home folder) and then
sudo mv
it to overwrite the original?将更改保存为另一个文件并进行适当的替换。
Save the changes as another file and the make the approrpiate replacement.
当 vim 启动时,状态栏显示
[readonly]
,并且第一次尝试编辑时,它显示W10: 警告:更改只读文件
并暂停第二。这足以让我退出并说sudoedit /etc/somefile.conf
。您可以使用插件强制执行此操作:使缓冲区可修改状态与文件只读状态。
When vim starts up, the statusbar says
[readonly]
, and the first time you try to edit, it saysW10: Warning: Changing a readonly file
and pauses for a full second. This is enough warning for me to quit and saysudoedit /etc/somefile.conf
.You can enforce this with a plugin: Make buffer modifiable state match file readonly state.
我使用 zsh 模板和函数完成。
具体来说这个。如果我没有写入权限,它会提示输入我的 sudo 密码并自动运行“sudo vim”……等等。
I use zsh templates and function completion.
Specifically this one. If I don't have write permissions, it prompts for my sudo password and automatically runs "sudo vim"…amongst other things.
我使用了这个:
我已将
映射到:w
。 &
到:call SaveAsSudo()
这个答案相对于
sudo tee
选项提供的唯一优势是:vim
不会抱怨未保存的缓冲区或外部修改的文件。I used this:
I have mapped
<F2>
to:w<CR>
. &<F8>
to:call SaveAsSudo()<CR>
Only advantage this answer provides over the
sudo tee
option is:vim
does not complain about unsaved buffer or file modified externally.