Execute current line in Bash from Vim

This could be a comment if I can comment.

Concerning redirect/pipe lines of current buffer in Vim to external command, inspired by Daan Bakker's great answer, I wrote I answer here (Save and run at the same time in Vim), on an question concerning running a Python script (current buffer).

Beside running the whole buffer, how to run a range of line via an external command is demonstrated.

To save time, I just copy it below.

#####################

In Vim, you could simply redirect any range of your current buffer to an external command (be it 'bash', 'python', or you own Python script).

# Redirect the whole buffer to 'python'
:%w !python

Suppose your current buffer contains the two lines as below,

import numpy as np
print np.arange(12).reshape(3,4)

then :%w !python will run it, be it saved or not. And print something like below on your terminal,

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Of course, you could make something persistent, for example, some keymaps.

nnoremap <F8> :.w !python<CR>
vnoremap <F8> :w !python<CR>

The first one runs the current line. The second one runs the visual selection, via the Python interpreter.

#!! Be careful, in Vim ':w!python' and ':.w !python' are very different, the
first writes (creates or overwrites) a file named 'python' with thew contents of
the current buffer. The second redirects the selected cmdline range (here dot .,
which mean current line) to an external command (here 'python').

For cmdline range, see

:h cmdline-ranges

Not the below one, which concerning normal command, not cmdline one.

:h command-range

This was inspired by Execute current line in Bash from Vim.


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('.')

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.


Move the cursor to that line, and in normal mode press:

!!bash<cr>

Tags:

Vim

Bash