David542
David542

Reputation: 110552

Pass filepath to a shell command in vim

How would I properly 'escape' the following command in vim?

:!file=expand('%:r')

Basically, I want to do the equivalent of something like:

$ file=my_filename

So that I can do a subsequent shell command to refer to $file. Currently I get this error:

Press ENTER or type command to continue
/bin/bash: -c: line 0: syntax error near unexpected token (' \ /bin/bash: -c: line 0: file=expand('test')'

Which I think just basically means that it's not escaping/generating the filename before passing to the shell. How would I do this?

Upvotes: 1

Views: 1169

Answers (3)

Matt
Matt

Reputation: 15196

  1. To pass filename/path to shell use command-line specials

    :!AnyShellCommand %:r
    
  2. To set environment variable use :let

     " like this
     :let $AnyEnvVar = expand('%:r')
     " or like this
     let $AnyEnvVar = fnamemodify(@%, ':r')
    

Upvotes: 2

yolenoyer
yolenoyer

Reputation: 9465

Maybe I missed something, but when you run :!myvar=42 then :!echo $myvar, you can see that the variable is not saved, certainly because it is run in two different shell sessions.

To make your variable accessible to every further shell commands, you can use setenv(): :call setenv('myvar', '42'), or in your case:

:call setenv('file', expand('%:r'))

Upvotes: 1

David542
David542

Reputation: 110552

You can wrap it in an execute, for example:

:execute  "!file=" . expand('%:r')

Upvotes: 0

Related Questions