Mar 082016
 

In a recent bash script, I needed to obtain the value of the $VIM environment variable. Vim uses $VIM (as well as $HOME and $VIMRUNTIME) when computing various paths: http://vim.wikia.com/wiki/Open_vimrc_file#Location_of_vimrc.

Default value of $VIM

It is possible to find the default (fall-back) value for $VIM by inspecting the output of running vim –version. Here’s a snippet of the output:

   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  system gvimrc file: "$VIM/gvimrc"
    user gvimrc file: "$HOME/.gvimrc"
2nd user gvimrc file: "~/.vim/gvimrc"
    system menu file: "$VIMRUNTIME/menu.vim"
  fall-back for $VIM: "/usr/share/vim"

The default value for $VIM can be grabbed with:

vim --version | sed -rn 's#[^$]+\$VIM: "([^"]+)"#\1#p' | tr -d '\n'

Similar commands can be used to parse the rest of the output (e.g. by replacing \$VIM: with system vimrc file:).

Actual value of $VIM

However, the real location might have been changed from this default. To get the actual location, one can echo the value of the environment variable itself and grab the output. Vim’s Ex mode is useful for this:

VIMENV=$(vim -E +'!echo $VIM' +qall < /dev/null | tr -d "\n")

Note that an input redirection from /dev/null is used to prevent Vim from attempting to blank the terminal. Without the redirection, the output will contain unwanted control characters. Also, in both of the previous snippets, the output is piped through tr -d "\n" to remove the trailing newline.

 Posted by at 10:48 pm

Leave a Reply