您的位置:首页 > 运维架构 > Shell

vim 执行shell命令技巧

2014-06-07 16:30 302 查看
:!cmd
不退出vim 执行命令 cmd

:r !cmd
不退出vim执行命令cmd,并将cmd的输出内容插入当前文本中。

:shell
切换到shell里(此时并没有退出vim,可以理解成vim转入后台),你可以在shell中做任何操作,退出shell(比如用exit)后,会切换回原来的vim中

vim保存root权限的文件

Linux,没有sudo 就直接用vim 编辑/etc/内的文件,等编辑好了之后,使用vim保存时,得到提示说文件无法保存,这时候才发现没权限。针对这种问题,目前有如下几种解决方案。
1. vi /etc/httpd.conf 保存时,用命令:w !sudo tee %
:w - Write a file.
!sudo - Call shell sudo command.
tee - The output of write (vim :w) command is redirected using tee. The % is nothing but current file name i.e. /etc/httpd.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself).
强烈推荐这一种用法。不过,首先得保证运行vim的用户有sudo的权限。

2.编辑用户$HOME/.vimrc文件将第一种方案的比较难记的命令重命名一下,下次可以直接使用。
vim $HOME/.vimrc 添加如下的一句话,并保存。
command -nargs=? Sudow :w !sudo tee %
今后用vim编辑时,需要sudo保存时,直接用此处定义的Sudow命令保存即可。

3. 先保存到一个临时文件中,然后用root去拷贝它去覆盖需要编辑的文件。
可能用user账号打开的一个文件,vim /etc/httpd.conf,然后在vim编辑号后,用:w /tmp/httpd.conf即可保存为一个临时文件。

4. 使用vim之时直接用sudo vim也可以,哈哈,如 sudo vim /etc/httpd.conf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: