2

When writing bash scripts in vim, it would be useful to be able to selectively run only a few lines from the script, e.g. if I have some script

#! /bin/bash

# more commands

mkdir /tmp/test_dir
echo "some output to STDOUT"
touch /tmp/test_dir/new_file

# more commands

say I just want to execute this part of the script

mkdir /tmp/test_dir
echo "some output to STDOUT"
touch /tmp/test_dir/new_file

how can I highlight and execute it in vim? I have tried

  • v, select target text, :

which gives a prompt with :'<, '>

then tried :! w

but its not working properly.
I dont need to write the STDOUT of the shell commands to a file or anything, but I would like to be able to at least see the output.

the_velour_fog
  • 2,094
  • 4
  • 17
  • 29
  • There is a Vim module called QuickRun that can do the same thing and give you the result in a split. It can execute the entire buffer or only part of it. https://github.com/thinca/vim-quickrun/blob/master/doc/quickrun.txt – Dan Lowe Sep 18 '15 at 13:37

2 Answers2

6

From the answer of pacholik, you can extrapolate:

in visual mode, hit : and write w !bash

so that your whole command is :'<,'>w !bash

You will get the output as a result (but it won't change the file

If you remove the w , it will instead replace the line by the output of the buffer.

I have for example mapped r to "run command" in visual mode.

Like this:

vnoremap r :w !bash<cr>

I also have this in normal mode (to run the current line), with yr (you run)

nnoremap yr :.w !bash<cr>
edi9999
  • 19,701
  • 13
  • 88
  • 127
0

You can use Quickrun plugin : http://vimawesome.com/plugin/quickrun-vim

It can run many languages on the fly (bash, python, c++...), and you can run only a selected area.

Everything you need is :

  • Set the filetype of your file (normally it's automatically detected, unless you created a new file, in this case just do for example : :set ft=sh for bash)
  • Select a part of your file with V.
  • Run :'<,'>QuickRun

The output opens in a new window. You can tweak the plugin on many points, see the help.

yolenoyer
  • 8,797
  • 2
  • 27
  • 61