2

I would like to capture the result of a shell command into a vim variable inside of my vimrc file.

I tried using let myvar = system("DIR") however it seems to crash vim when I put it in my vimrc file. I launch vim and then it just returns immediately without any error message.

So instead I was wondering if I can do something like let exe_path = <expr> :!pwd ? This is obviously the wrong way to do it so I was wondering if something like that is possible?

  • 1
    the suggested system() command should work. Questions is, what you mean with it is crashing vim. That should not happen. – Christian Brabandt Nov 28 '19 at 10:37
  • 1
    let myvar = system('pwd') is the way to go as described in this duplicate question on my system it works fine. I think you used the wrong tag and meant microsoft-windows so are you sure your Windows shell supports pwd (it's been a long time since I haven't used a windows shell so I don't remember if it's supported) maybe you should try with another command ? – statox Nov 28 '19 at 10:37
  • 2
    system() definitely is the function you're looking for; rather than asking for an alternative, please post more details about that "crash". – Ingo Karkat Nov 28 '19 at 10:38
  • 1
    As Christian mentioned, that should not happen. On the other hand, invoking an external command during startup would be bad for startup time (especially on Windows), anyway. Can't you do this lazily, on demand? You could also try to execute this on :autocmd VimEnter * let myvar = system('pwd'); it's still on startup, but at the end of it. – Ingo Karkat Nov 28 '19 at 12:33
  • 3
    If the only thing is to get the curdir then let myvar = getcwd() makes more sense than system(). – Matt Nov 28 '19 at 12:45
4

system() is the right function; it should work fine also inside ~/.vimrc, but is best avoided as each external command delays Vim's startup and makes the user wait.

Ideally, you'll be able to only invoke the external command once it's required for a user interaction (i.e. lazily) - and then cache the information in case it's needed again.

If you absolutely need the information on startup already, and to work around your problem, you can hook into the VimEnter event that is fired at the end of initialization:

:autocmd VimEnter * let myvar = system('pwd')

The pwd is only an example; you'd better use the built-in getcwd() instead.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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