Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute current line in Bash from Vim

Tags:

bash

vim

This question is similar to Vim: execute current file?, but instead of executing the current file I want to execute only the current line.

Is this possible?

Ideally, I am looking for solutions which can have side effects in the outer shell.

For example, suppose I have the following line:

alias foo=bar 

After running the command in Vim, if I start a shell with :sh, the alias foo is available, but if I quit vim using :q, then the alias is no longer available.

like image 747
merlin2011 Avatar asked Nov 09 '13 22:11

merlin2011


People also ask

Can you run commands from Vim?

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.

How do I run a script in Vim?

You can always execute Vimscript by running each command in command mode (the one you prefix with : ), or by executing the file with commands using a :source command. Historically, Vim scripts have a . vim extension. Here, :so is a short version of :source , and % refers to the currently open file.

How do I find the command line in Vim?

You can also open the Vim : command line by pressing Ctrl-W : . The other Ctrl-W commands work as normal, so managing windows works the same no matter what type of window is currently selected.


2 Answers

Sure thing, you can 'write' any content of the current file into the standard input of another program:

:.w !bash 

Here . (the part before w) refers to the range of lines you are writing, and . is only the current line. Then you use !bash to write those lines to Bash.

like image 193
Daan Bakker Avatar answered Sep 17 '22 08:09

Daan Bakker


I do this sort of thing all the time with:

:exec '!'.getline('.') 

You can even create a mapping in your .vimrc:

nmap <F6> :exec '!'.getline('.') 
like image 36
cforbish Avatar answered Sep 17 '22 08:09

cforbish