Automatically chdir to vagrant directory upon "vagrant ssh"

Solution 1:

I put

echo "cd /vagrant_projects/my-project" >> /home/vagrant/.bashrc

in my provision.sh, and it works like a charm.

Solution 2:

cd is a Bash shell built-in, as long as a shell is installed it should be there.

Also, be aware that ~/.bash_profile is for interactive login shell, if you add cd /vagrant in ~vagrant/.bashrc, it may NOT work.

Because distros like Ubuntu does NOT have this file -> ~/.bash_profile by default and instead use ~/.bashrc and ~/.profile

If someone creates a ~/.bash_profile for vagrant user on Ubuntu, ~vagrant/.bashrc will not be read.

Solution 3:

You can do this by using the config.ssh.extra_args setting in your Vagrantfile:

  config.ssh.extra_args = ["-t", "cd /vagrant; bash --login"]

Then anytime you run vagrant ssh you will be in the /vagrant directory.

Solution 4:

You need to add cd /vagrant to your .bashrc in the vm. The best way to do this is in your provisioner script.

If you don't have a provisioner script, make one by adding this line to your Vagrantfile before end:

config.vm.provision "shell", path: "scripts/vagrant/provisioner.sh", privileged: false

Path is relative to the project root where the Vagrantfile is, and privileged depends on your project and what else is in your provisioner script which might need to be privileged. I use priveleged false and sudo explicitly when necessary.

And in the provisioner script:

if ! grep -q "cd /vagrant" ~/.bashrc ; then 
    echo "cd /vagrant" >> ~/.bashrc 
fi 

This will add cd /vagrant to .bashrc, but only if it isn't there already. This is useful if you reprovision, as it will prevent your .bashrc from getting cluttered.

Some answers mention a conflict with .bash_profile. If the above code doesn't work, you can try the same line with .bash_profile or .profile instead of .bashrc. However, I've been using vagrant with ubuntu guests. My Laravel/homestead box based on Ubuntu has a .bash_profile and a .profile but having cd /vagrant in .bashrc did work for me when using vagrant ssh without changing or deleting the other files.

Solution 5:

You can add cd /vagrant to your .bashrc and it will run the command when you ssh. The /bashrc you want is in /home/vagrant (the user you login as when you vagrant ssh.) You can just stick the new line at the bottom of the file.