Search code examples
vimsh

display STDOUT in vim when external command fails


I need to run external command in vim and see the stdout only if it fails.

For example when I hit F9 i want to run do.sh and be informed only about the errors. Now I use double <cr><cr> to close the default output window but this will not show me any errors:

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

Solution

  • This can be done easily with the system() function and the v:shell_error variable. Put the following in your .vimrc file.

    nnoremap <leader>n :call Foo()<cr>
    
    function! Foo()
      let bar = system('script.sh')
      if v:shell_error
        echo bar
      endif
    endfunction
    

    As a bonus, there's no need for the double <cr> because system() returns the output without displaying anything.