VimL: is it possible to output the output of an `exec` command, inside a variable?
To execute an external command and capture its output in a Vim variable, use system()
:
:let hostname = system('hostname')
The command is called through configured 'shell'
; as long as your Bash script has the correct shebang ( #!/bin/bash
) line, you should be fine.
If you end up wanting to insert the output into the current buffer, you can also use :read !{cmd}
directly:
:read !hostname
source to share
As an alternative approach, note that the default signature for the operator is let
:
let {var} = {expr}
where the right side should be an expression. This means it let
cannot execute the command output execute
. In other words, try:
let {var} = {cmd}
will result in an error. A workaround is to use a command redir
that has the following syntax:
redir => {var} {cmd} redir end
See how this works in practice. Try first:
let somevar = echo "The current locale settings are: " . v:lang
returns error E15: Invalid expression . Now using
redir => somevar
echo "The current locale settings are: " . v:lang
redir end
the error disappeared and the variable was successfully allocated, which is confirmed by printing its value:
echo somevar
with output:
The current locale settings are: en_US.UTF-8
source to share