9

Calling the function system("<command>") or systemlist("<command>") retrieves the stdout output from a shell call to <command>. How can I retrieve the exit status of that command?

For example, I would like to do something like this:

let output =  system_call_with_exit_status("my_shell_command")
let stdout = output[0]
let exit_status = output[1]
if (exit_status != 0)
    echo output
endif

The intention is to print the output from my_shell_command only if the command gives a non-zero exit status.

4
  • 7
    :h v:shell_error Apr 28, 2019 at 16:43
  • @ChristianBrabandt Thanks, that works.
    – Jasha
    Apr 28, 2019 at 16:57
  • @Jasha consider self-answering if youve got it figured out now
    – D. Ben Knoble
    Apr 28, 2019 at 17:06
  • @D.BenKnoble Ok, will do.
    – Jasha
    Apr 28, 2019 at 17:08

2 Answers 2

16

Mentioned in the comments above, the v:shell_error variable gives the result of the last shell command. So the exit status can be tested as follows:

let output = system("my_shell_command")
if v:shell_error != 0
    echo output
endif
1

If you use Lua, the following utility function also helps:

function shell_error()
  return vim.v.shell_error ~= 0
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.