2015年7月8日 星期三

[Linux 常見問題] Getting root permissions on a file inside of vi?

Source From Here 
Question 
Often while editing config files, I'll open one with vi and then when I go to save it realize that I forget the "sudo". For example: 
# sudo vi filename

Is there any way to give vi sudo privileges to save the file while already opening the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it. 

How-To 
Refer to below command inside command-line mode. % is replaced with the current file name, thus you can use: 
:w !sudo tee %

vim will detect that the file has been changed and ask whether you want to it to be reloaded. 

As a shortcut, you can define your own command. Put the following in your ~/.vimrc
  1. command W w !sudo tee % >/dev/null  
With the above you can type :W to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this: 
  1. cmap w!! w !sudo tee >/dev/null %  
This way you can type :w!! and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the % with a file name of your own, if you like.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...