5

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

1
  • let s = execute(":! echo dani") | echo s does return dani for me. maybe you should post your real function call Commented Oct 25, 2018 at 5:43

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the thorough answer! Especially for showing alternatives and how they work!
Ah, glad I could help! Please accept the answer by clicking on the outlined checkmark. This way, the question is marked as closed, and you increase your chances of getting answers to future questions, as this shows that you care about the answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.