如何从Shell命令行运行vim命令?

77

有很多关于如何在vim中运行shell程序的stackoverflow问题。现在反过来,也就是说:

$ vim :BundleInstall

我想在shell脚本中运行BundleInstall而不是手动打开vim运行它,有什么方法可以实现吗?

5个回答

108

注意,现在语法已经改变,应该按照以下方式进行编写(根据 @sheharyar 的说法):

vim +PluginInstall +qall

为了后人记录,之前的正确代码是:

vim +BundleInstall +qall

如果有人正在浏览,请注意!注:这是在 vundle 的Github README中提到的。


4
如果你需要传递参数:echo '{"foo":"bar", "baz":{"baa":0,"bao":1}}' | vim "+setf json" - - risto
2
要执行多个命令,例如对于vim-plug:vim +PlugInstall +PlugClean! +qall - thiagowfx

36

根据vim手册man vim):

+{command}

-c {command}
    {command}  will  be  executed after the first file has been
    read.  {command} is interpreted as an Ex command.   If  the
    {command}  contains  spaces  it  must be enclosed in double
    quotes (this depends on the shell that is used).   Example:
    Vim "+set si" main.c
    Note: You can use up to 10 "+" or "-c" commands.

或者:

--cmd {command}
    Like using "-c", but the command is  executed  just  before
    processing  any  vimrc file.  You can use up to 10 of these
    commands, independently from "-c" commands.

这要看你想做什么。另外,正如在vundle的自述文件中所描述的那样,如果您以这种方式启动vim:

    vim +BundleInstall +qall
这将安装所有捆绑选项而无需打开vim。仅供澄清,以下是从vim文档中摘录的内容:
:qall

    This stands for "quit all".  If any of the windows contain changes, Vim will
    not exit.  The cursor will automatically be positioned in a window with
    changes.  You can then either use ":write" to save the changes, or ":quit!" to
    throw them away.

4

有没有更复杂的内容?

vim "+set ff=unix" "+wq" node_modules/less-monitor/bin/less-monitor

我不确定这是否完全正确,但对我有效。感谢@jvc26


我无法理解这是一个新问题(则应分别提出)还是一个新答案。 - Fabio says Reinstate Monica
1
这只是一个示例,展示如何使用类似于+set ff=unix的多单词命令,并且使用+wq代替+qall。在我的情况下,我需要更新文件。我将其发布为答案,因为我无法发布评论(需要50+声望)。 - graceman9

2
我将为需要更通用解决方案的人提供另一个答案。 vim +command 可以运行一个 Vim 命令,但是如果要从 shell 运行多个 Vim 命令,则可以在 Ex 模式下启动 Vim 并使用 Here document 提供命令。这是我编写的一个脚本示例。它会在文件中搜索一个模式并在其前插入一些文本。
    ex --noplugin +1 "$v_file" <<-END 
            set maxmempattern=8000
            /^\s*\<endmodule\>/i

            FIXME   \`ifdef XXX_INCLUDE_API
              \`include "${api_file}"
            \`endif

            .
            w
            q
    END

0

这个

vim --cmd BundleInstall

你想做什么?


在加载插件后,您需要执行命令。使用“-c”选项。 - kev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接