Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim sending empty buffer to shell

Tags:

bash

vim

Vim newb here. I'm trying to understand the behaviour of this documented function:

                                                    *:w_c* *:write_c*
:[range]w[rite] [++opt] !{cmd}
                        Execute {cmd} with [range] lines as standard input
                        (note the space in front of the '!').  {cmd} is
                        executed like with ":!{cmd}", any '!' is replaced with
                        the previous command |:!|.

I tried the following:

  • Open vim
  • go to insert mode and type the text 'foo'
  • Enter the ex command :w ! touch

I expected this to create a file named 'foo', as typing 'touch foo' does in the shell. Instead I get this error:

:write ! touch
usage:
touch [-A [-][[hh]mm]SS] [-acfhm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...

shell returned 1

It's like it's sending an empty buffer to touch. I tried saving the file to see if that made a difference but it did not. I'm reading the book 'Practical Vim' which gives this example:

:write ! sh

will run the contents of the buffer as shell commands. If I change foo to echo foo and run this command I get the expected behaviour:

:w ! sh
foo

Thanks in advance for any help.

like image 848
rwold Avatar asked Jun 09 '26 22:06

rwold


1 Answers

The "bang" command passes buffer contents through stdin. But "touch" expects its argument on the command line.

To "connect" the two things use xargs utility.

:w !xargs touch
like image 191
Matt Avatar answered Jun 12 '26 11:06

Matt