Daniel Hernandez
Daniel Hernandez

Reputation: 683

Saving return value of "execute" function into variable vimscript

In vimscript, I cannot find the way of saving the return value of the execute function into a variable.

I would like to do the following:

let s = execute(":!echo dani")
echo s

This should return: dani

Vim doesn't accept this. In my setup (using vim-airline and other UI plugins) the screen blanks all content and upon a key press it goes back to normal.

Is it possible in vimscript to save into a variable the return of either a function call, or conversely the return of the execute function?

Thanks SO

Upvotes: 4

Views: 3455

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172510

execute() is the modern alternative to :redir; it does capture all output of the executed command. Let's look a bit more closely:

:let s = execute(":! echo dani") | echo strtrans(s)
^@:! echo dani^M^@dani^M^@

As you can see, it captures the entire command and its result. If you use plain :echo, the newlines and ^@ obscure the full output (you'll see it better with :echomsg, which does less interpretation of special characters).

I think what you really want is just the output of the executed external command (here: echo). You can use system() instead of :! for that:

:let s = system('echo dani') | echo strtrans(s)
dani^@

That trailing newline usually is removed like this:

:let s = substitute(system('echo dani'), '\n\+$', '', '') | echo strtrans(s)
dani

Upvotes: 14

Related Questions