9

I want to execute an external command in Vim script but I don't how can I do this. For example I need to change a file permission using chmod command (Please assume application has enough permission to run the command)

Is there any way to achieve this?

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201

3 Answers3

9

If you want users to see the output (or interact with the command) :! is the right command. For silent execution (as I suppose would be desired with your chmod), using system() is preferable. Especially on Windows, this avoids the popup of a command prompt that must be dismissed manually.

:call system('chmod +x ' . shellescape(fname))
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
6

You can use the :! vim command. For example, to echo 'Hello, World!' from inside vim (and therefore from within a vim script, also), type

:! echo 'Hello, World\!'

in vim. Or, in a vim script, you can put just

! echo 'Hello, World\!'

The reason you need the \ before the ! is because vim performs special handling of ! characters in the argument of a ! command. If you were running a command that does not include any ! character, then you do not need to escape it.

If you want to read more in depth about this, you can type

:help :!

in vim, as @FDinoff said.

feralin
  • 3,268
  • 3
  • 21
  • 37
2

My preferred way is to push Ctrl-z or run :sus to suspend the vim process, then you can do whatever you want in the shell.

When you are done, run fg (foreground) to resume your vim session.

More info can be found here.

Community
  • 1
  • 1
Cao Minh Tu
  • 553
  • 5
  • 12