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?

1

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution. Is there any way to get the output of call system() and show it manually to the user? For example via echo() command in Vim.
It returns the output, and the exit status is in v:shell_error. :help system() is your friend :-)
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.

1 Comment

Also make sure to look at :h :!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.