Vagrant SSH Command Shortcut

Vagrant is a tool that is all about distributing a development Virtual Machine (VM) that all the devs on a project can easily set up and so all devs can be working in the same environment.

It has a neat little feature that will sync your folders on the host to the guest VM, so you don't even have to SSH into the guest VM do most actions.

Occassionally, however, you need to run a command directly on the guest VM, such as a migration. Normally, you have to either run vagrant ssh and then change the directory to where the project is (it's very common to create an alias on the guest that points to the project root in the form of /vagrant/), run the command and then exit to get back to your normal shell.

Or, you can combine that into one command:

vagrant ssh -c "cd /vagrant && command to run"  

But that is a lot to type out every time!

So I created a little "Vagrant user do" bash function (just place this in your .bashrc (or, if you're like me, your .zshrc)):

function vudo() {  
  eval "vagrant ssh -c \"cd /vagrant && $@\""
}

Usage:

$ vudo composer update
$ vudo php artisan migrate
$ vudo anycommandyouwanttorunonyourvmfromyourvagrantfolder

Now you can quickly and easily run one-off commands in your VM with very little effort.