外部命令失败时在vim中显示STDOUT

时间:2014-09-26 03:40:18

标签: vim sh

我需要在vim中运行外部命令,只有在STDOUT失败时才能看到它。

例如,当我点击F9时,我想运行do.sh并仅被告知错误。现在我使用double <cr><cr>关闭defualt输出窗口,但这不会显示任何错误:

nmap <F9> :!./script.sh<cr><cr>

2 个答案:

答案 0 :(得分:1)

使用做得好的工具:shell。像这样的包装可以解决这个问题:

 #!/bin/sh
 #
 # Run the program specified by the args silently and show stdout on failure.

 if ! "$@" >stdout 2>stderr; then
    cat stdout stderr
 fi

您可以在vim映射中填写此内容。稍短的版本可能是:

 ./script.sh > stdout || cat stdout

答案 1 :(得分:1)

使用system()函数和v:shell_error变量可以轻松完成此操作。将以下内容放在.vimrc文件中。

nnoremap <leader>n :call Foo()<cr>

function! Foo()
  let bar = system('script.sh')
  if v:shell_error
    echo bar
  endif
endfunction

作为奖励,不需要双<cr>因为system()返回输出而不显示任何内容。