Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VimL: capture output of `exec` command, inside a variable is possible?

Tags:

vim

I have some bash scripts and I need to retrieve them output from a Vim script. Is it possible? If yes, how?

like image 431
sensorario Avatar asked May 18 '15 11:05

sensorario


2 Answers

To execute an external command and capture its output in a Vim variable, use system():

:let hostname = system('hostname')

The command is invoked through the configured 'shell'; as long as your Bash script has a proper shebang line (#!/bin/bash), everything should be fine.

If you eventually want to insert the output into the current buffer, you can alternatively use :read !{cmd} directly:

:read !hostname
like image 106
Ingo Karkat Avatar answered Nov 11 '22 21:11

Ingo Karkat


As an alternative approach, note that the default signature of the let statement is:

let {var} = {expr}

where the right hand side must be an expression. This means that let cannot capture the output of an execute command. In other words, trying:

let {var} = {cmd}

will produce an error. A workaround is to use the redir command, which has the following syntax:

redir => {var}
{cmd}
redir end

Let's see how it works in practice. First trying:

let somevar = echo "The current locale settings are: " . v:lang

returns the error E15: Invalid expression. Now with:

redir => somevar
echo "The current locale settings are: " . v:lang
redir end 

the error is gone and the variable was successfully allocated, which is verified by printing its value:

echo somevar

with output:

The current locale settings are: en_US.UTF-8
like image 4
builder-7000 Avatar answered Nov 11 '22 21:11

builder-7000