I have some bash scripts and I need to retrieve them output from a Vim script. Is it possible? If yes, how?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With