How would I go about using a variable in a vim shell command (one done with !
) in a vimscript? For instance, something kind of like this: (just an example, not what I'm really trying to do)
function Ls(dir) !ls a:dir endfunction
You can run commands in Vim by entering the command mode with : . Then you can execute external shell commands by pre-pending an exclamation mark ( ! ). For example, type :! ls , and Vim will run the shell's ls command from within Vim.
Vim's scripting language, known as Vimscript, is a typical dynamic imperative language and offers most of the usual language features: variables, expressions, control structures, built-in functions, user-defined functions, first-class strings, high-level data structures (lists and dictionaries), terminal and file I/O, ...
Use the execute
command. Everything after it is an expression that evaluates to a string, which it then executes like a command you had typed in yourself.
function Ls(dir) execute '!ls ' . a:dir endfunction
This says, "Evaluate the expression '!ls ' . a:dir
and then execute it." The variable a:dir
is expanded, the dot concatenates the two strings into '!ls whatever'
and then that is executed as if you had typed it.
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