Is there a way for a bash script to determine if it's being run from within vim?

I'm writing a small bash script that is only useful if called within vim. I'd like to assure that it only does its thing within vim, and that if called from the shell, it reports an error. I'm wondering if vim offers some environment variable (or the like) for which I can test.

EDIT: I figured out I can use the following, but it feels "hackish" to me. I'd love something better if it exists.

[ -z $VIMRUNTIME ] && \
    { echo "This script is to be run from inside vim" ; exit ; }
  • 1
    You are testing for an environment variable that only exists in shells started in Vim. How is that "hackish"?
    – romainl
    Oct 22, 2022 at 8:15
  • @romainlI I'm not adept enough at this stuff to say it is. I said it feels "hackish to me. That variable wasn't put there for the purpose for which I'm using it, but for something else. I'm trying to learn if Bram put something in vim specifically to determine if an external command is doing something. This isn't a moral or ethical issue for me; it's an "am I doing this the optimal way" thing.
    – MDeBusk
    Oct 22, 2022 at 14:15

1 Answer 1


Usually it is okay just to test environment variables, such as $VIM or $VIMRUNTIME (or even $MYVIMRC, although the latter is not guaranteed to exist). This is very easy and portable.

But, of course, you can employ some alternative method, such as inspecting your parent process attributes. For example,

[[ "$(cat /proc/$PPID/comm)" =~ ^[gn]?vim$ ]] && echo "Was run by (some kind of) Vim"

But I doubt it could bring any real benefits.

  • The latter is of course highly OS specific.
    – D. Ben Knoble
    Oct 22, 2022 at 13:16
  • @D.BenKnoble At least, it should work on most Linuxes. But, for sure, anything related to process management is OS specific.
    – Matt
    Oct 22, 2022 at 13:39
  • Something like $(ps -ho comm $(ps -ho ppid $$)) should be fairly portable... I think... But it's not that important because using $VIMRUNTIME is fine. Oct 23, 2022 at 4:15

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.