Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically chdir to vagrant directory upon "vagrant ssh"

So, I've got a bunch of vagrant VMs running some flavor of Linux (centos, ubuntu, whatever). I would like to automatically ensure that a "vagrant ssh" will also "cd /vagrant" so that no-one has to remember to do that whenever they log in.

I've figured out (duh!) that echo "\n\ncd /vagrant" >> /home/vagrant/.bashrc will do the trick. What I don't know is how to ensure that this only happens if the cd command isn't already there. I'm not a shell expert, so I'm completely confused here. :)

like image 203
Rob Kinyon Avatar asked Jul 25 '13 16:07

Rob Kinyon


4 Answers

I put

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

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

like image 176
httpete Avatar answered Oct 22 '22 13:10

httpete


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.

like image 24
q0rban Avatar answered Oct 22 '22 13:10

q0rban


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.

like image 27
Terry Wang Avatar answered Oct 22 '22 12:10

Terry Wang


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.

like image 7
Menasheh Avatar answered Oct 22 '22 13:10

Menasheh