Let's say I have the following script:

sudo apt update
sudo apt upgrade
sudo apt install jq
sudo apt install jo

If I use the command :set makeprg=bash\ % | make inside Vim, the system will ask me my password and then it'll execute this entire script. However, I'd like to find a way of executing only the lines that I select... Let's say I go to the third line inside this file and I press V to select only the third line, is there any way of making Vim execute interactively only this line?


A couple:

  • :[range]w !{program} uses a range to only write selected lines as standard input. This doesn’t work if you need to run it differently.
  • ! is similar but replaces the range with the output.
  • Delete the non-interesting lines, write the file, and run it. Then undo and write again.
  • You could probably make an operator and visual mapping that ran bash -c …, but you would want to think about using single quotes, escaping them in the arguments, and maybe even joining lines together.
  • Run :terminal for a shell and copy-paste
  • Run :terminal <C-r>=getline('.') to directly run the current line (no shell)
  • Interesting that ! doesn't require saving the file as it usually does when I'm working with selected lines. I didn't manage to make :[range]w !{program} work though. does the range word mean the line numbers? What does the {program} syntax do? I've tried stuff like :[4-7]w !{%}, :[4-7]w !{program} and the literal :[range]w !{program}... But it's not clear to me how I'd use it...
    – raylight
    Jun 22 '21 at 3:37
  • 1
    Those are placeholders @raylight See :help range. Replace the curly braces too with your program name (eg bash)
    – D. Ben Knoble
    Jun 22 '21 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.