Given this command:

ex -sc '%!alfa' -cx file

I get this result:

sh: alfa: command not found

which is to be expected. However an unintended side effect of this is that the file is emptied and saved.

Can this command be modified so that if the external command is not found, then Vim bails instead of saving an empty file?

  • Cannot replicate on Linux/Vim7.4, the exact same command: fails (because of "alfa" which does not exist), opens a new buffer but does not save a file. How exactly are you running it? My best try to replicate it was: echo data > file1 ; vim -u NONE -c "ex -sc '%\!alfa' -cx file2" file1
    – grochmal
    Commented Jul 10, 2016 at 19:32
  • I actually did that from the command line. It was mostly to highlight the fact that i'm using -u NONE (which is a good idea when debugging something). In general i'm confused about what exactly you are performing just as much you are confused about what i am performing. But you are the one with a question, can i ask you to elaborate exactly what you're running? Is it a command-mode ex (a : normal-mode command)? Or you're entering ex-mode? Or you're running ex from the command line?
    – grochmal
    Commented Jul 10, 2016 at 20:31
  • I may be wrong (this is purely from experience) but running the ex command in vim behaves differently from running the ex binary. Not all systems have ex as a call to vim -e. But now I get you. I can replicate it with vim -u NONE -e -sc '%!alfa' -cx file (i believe that is the portable command, not sure if -u NONE is needed)
    – grochmal
    Commented Jul 10, 2016 at 21:48
  • 1
    I'd argue it is a bug. Vim does not figure out correctly that the buffer has not been changed. vim -e -scx file works as expected but even vim -e -sc '%!echo >/dev/null' -cx file writes the empty file.
    – grochmal
    Commented Jul 10, 2016 at 22:11

2 Answers 2


You can use v:shell_error to test whether the external command succeeded or failed. Typically a non-zero result means the command failed.

In that case, you can use :q! to exit the Ex script with the file unmodified. Or, perhaps better, use the :cq! command to have Ex/Vim exit with a non-zero exit code, so your script calling Ex can also detect that something went wrong.

For example:

$ ex -s -c '%!alfa' -c 'if v:shell_error|cq!|endif' -c 'x' file
sh: alfa: command not found
$ echo $?
$ cat file
(Original contents of file.)

As a workaround, I am now using the shell builtin type alfa before the Vim call.

Your Answer

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

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