Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

From inside Vi/Vim, I can type:


to drop into a shell.

Is there any way to detect that I am in a Vi-spawned subshell?

The environmental variable SHLVL is 2, but that does not tell me explicitly that I am in a Vi/Vim-spawned subshell.

On OS X, the following variables are also set: MYVIMRC, VIMRUNTIME, VIM.

How universal are these? Can I count on these being set in any system, if and only if I am in a Vi/Vim subshell?

If not, is there any portable, robust and hopefully efficient way to tell that I am in a Vi/Vim subshell?


share|improve this question
up vote 2 down vote accepted

I see those same variables in Ubuntu 9.10 with Vim 7.2 and under Cygwin 1.7 with Vim 7.2 under Vista.

Here is the documentation.

Note that MYVIMRC may not be present if there's no .vimrc file.

share|improve this answer
same here on Debian Lenny, vim 7.1. i get SHLVL 2 in screen as well (SHLVL 3 when in a vim-spawned subshell in one of those screen windows) so SHLVL itself probably isn't a good test. perhaps SHLVL>1 and one or more of VIM, VIMRUNTIME, MYVIMRC – quack quixote Mar 26 '10 at 23:11
If you find that sometimes one of those is set outside of vim (since they are configuration variables for vim), you could use let $UNDER_VIM='Yes, probably.' in your .vimrc and check test -n "${UNDER_VIM:-}" in your shell. Or if your shell has PPID, use ps to lookup the command for it and see if it looks like vim (could be vim, vi, rvim, evim, view, rview, etc.). – Chris Johnsen Mar 27 '10 at 0:45
@Chris: Except that rvim and rview won't let you :shell. – Dennis Williamson Mar 27 '10 at 1:36
Thanks for the info. Chris Johnsen -- your "let $UNDER_VIM='Yes, probably.'" idea works perfectly. ... THANKS! – Jeet Mar 27 '10 at 2:31
@Chris: By the way, why are using a default to null in your test? I don't see any difference between yours and test -n "${UNDER_VIM}. – Dennis Williamson Mar 27 '10 at 3:49

I don't know OSX too well, but if it has a /proc filesystem, you can probably check the name of the parent process, like this:

if expr match $parent $(which vim) > /dev/null
share|improve this answer
No /proc filesystem, I'm afraid. Though the concept could be implemented as follows: if [ $(ps -o command -p $(ps -o ppid -o command -p $$ | tail -1 | awk '{print $1}') | tail -1) == vi then ... fi Pretty awkward though! – Jeet Mar 27 '10 at 2:27
Wouldn't this be enough? : ps -o command -p $PPID – njd Mar 27 '10 at 14:20
njd: it indeed would. Did not realize that $PPID was exported. Thanks! – Jeet Mar 28 '10 at 8:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .