I would like to execute source ~/.bashrc every time I finish editing a file with vim (i.e. after :wq vim command).

How should I configure vim or bash to work that way?

  • That's a bad idea: if you accidentally include something wrong in your .bashrc, that might cause the shell to exit. Test it in a separate terminal — it's more convenient anyway. – Gilles Jul 10 '14 at 20:53

A direct way to do it:

vim ~/.bashrc && source $_

You can make an alias:

alias vimbashrc='vim ~/.bashrc && source $_'

This works in bash or zsh. In other shell, you must explicit name .bashrc to source to make it work:

alias vimbashrc='vim ~/.bashrc && source ~/.bashrc'

There is a hook that you can use to have vim execute a command after writing a file. For example here I use it to auto-reload vim's rc file after saving:

autocmd BufWritePost $MYVIMRC source $MYVIMRC

Unfortunately this will not help you at all with what you want to do. This is because the commands that get run are executed as children of the vim process. No matter what you do there, the parent environment is not going to be affected.

What you really need is something up at the shell level. Start by looking at what you are doing:

vim  ~/.bashrc
source ~/.bashrc

But really you only want the latter if the first is successful:

vim ~/.bashrc && source $_

Now all you need is a convenience command that makes that easier to type:

function vbrc () {
    vim ~/.bashrc && source $_

Now to edit your bashrc file, just run vbrc and it will source it when you're done editing.

The other handy thing to do for testing changes to your bashrc would be to run a shell as a sub-process in vim. This would allow you to quickly test saved changes in shell. When you drop back out of the shell you'll be back editing the file.


You could even wire that up to the save hook so that every time you saved the file it would force you to check the results inside a live shell. Obviously this is only useful in the context of actively developing your rc so you'll probably want to activate this manually rather than from your vimrc:

autocmd BufWritePost ~/.bashrc !bash

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.