I am trying to redirect the output of a bash command into a new file.

If I try the pipe as below :

ls -la | vim

Bash shows me the errors :

Vim: Error reading input, exiting...
Vim: preserving files...
Vim: Finished.

I know that I can open Vim and then use :

:r !ls -la

But is there a way to do this in bash itself, so that Vim is opened and the output is pasted there automatically?


You can use process substitution (this also works with applications that can't read from STDIN):

vim <(ls -la)

Or use vim's function to read from STDIN:

ls -la | vim -
| improve this answer | |

You're really close on your own. You were just missing one character.

ls -la | vim -
| improve this answer | |
  • 12
    Well technically it's two characters. ;) – Cory Klein Oct 24 '17 at 22:14

Here's another approach, hopefully to teach someone something new.

If you know that the command :r !ls -la works inside vim, you can do the following to open vim and make it run the command as soon as it opens, straight from bash:

vim -c ':r! ls -la'

This is the equivalent of opening vim then executing the command :r! ls -la. This should work with any vim command, where the command comes after the -c option.

| improve this answer | |

You can tell vim to open stdin:

ls -la | vim -
| improve this answer | |

If your goal is simply to get the output into a text file then you don't need to invoke vim. Bash can do it alone with

ls -la > outputfile.txt
| improve this answer | |

setlocal buftype=nofile

This is a good option if you are going to create an alias to replace less:

seq 100 | vim +':setlocal buftype=nofile' -

Now you don't need to type the ! to quit.

Another option is:

seq 100 | vim +'nnoremap q :quit!' -

so you can exit with just q<enter>.

| improve this answer | |
  • Good idea. Definitely shorter than typing this long ! :) – kode Jun 21 '17 at 15:04

I would like to add an option

ls -al | view -

view is a read-only version of vim(equivalent to vim -R)

| improve this answer | |

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.