45

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. :)

4

8 回答 8

29

我放

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

在我的provision.sh,它就像一个魅力。

于 2014-09-19T14:21:34.400 回答
27

cd是内置的 Bash shell,只要安装了 shell,它就应该在那里。

另外,请注意,这~/.bash_profile是用于交互式登录 shell,如果您添加cd /vagrant~vagrant/.bashrc它可能无法正常工作。

因为像 Ubuntu 这样的发行版默认没有这个文件 ->~/.bash_profile而是使用~/.bashrcand~/.profile

如果有人~/.bash_profile在 Ubuntu 上创建了一个 for vagrant 用户,~vagrant/.bashrc则不会被读取。

于 2013-07-29T21:18:51.583 回答
27

你可以通过使用config.ssh.extra_argsVagrantfile 中的设置来做到这一点:

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

然后,无论何时运行vagrant ssh,您都会在/vagrant目录中。

于 2019-08-01T16:40:35.910 回答
6

您需要cd /vagrant在 vm 中添加到您的 .bashrc。最好的方法是在您的配置脚本中。

如果您没有配置器脚本,请在之前将这一行添加到您的 Vagrantfile 中end

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

路径相对于 Vagrantfile 所在的项目根目录,特权取决于您的项目以及您的配置程序脚本中可能需要特权的其他内容。必要时,我会明确使用 priveleged false 和 sudo。

在供应商脚本中:

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

这将添加cd /vagrant到 .bashrc,但前提是它不存在。如果您重新配置,这很有用,因为它会防止您的 .bashrc 变得混乱。

一些答案提到了与 .bash_profile 的冲突。如果上面的代码不起作用,您可以尝试在同一行中使用.bash_profileor.profile代替.bashrc. 但是,我一直在使用 vagrant 和 ubuntu 客人。我基于 Ubuntu 的 Laravel/homestead 盒子有 a.bash_profile和 a.profilecd /vagrant在使用时.bashrc 确实vagrant ssh对我有用,而无需更改或删除其他文件。

于 2018-02-11T01:09:24.603 回答
4

您可以添加cd /vagrant到您的.bashrc,它会在您 ssh 时运行该命令。您想要的/bashrc/home/vagrant(您登录时的用户vagrant ssh。)您可以将新行粘贴在文件的底部。

于 2013-07-26T16:43:47.870 回答
4

你也可以这样做:

vagrant ssh -c "cd /vagrant && bash"

您可以将其包含在脚本中以启动它(如./vagrant-ssh)。

于 2018-11-23T10:35:33.620 回答
2

可能这会有所帮助。编辑Vagrantfileas 替换您的用户名vagrant

`
 config.vm.provision "shell" do |s|
 s.inline = <<-SHELL
 # Change directory automatically on ssh login
 if ! grep -qF "cd /home/vagrant/ansible" /home/vagrant/.bashrc ;
 then echo "cd    /home/vagrant/ansible" >> /home/vagrant/.bashrc ; fi
 chown vagrant. /home/vagrant/.bashrc
` 
于 2017-11-21T06:25:39.233 回答
1

理想情况下,我们只想改变 vagrant ssh 行为。

就我而言,我想要一些不会影响环境中任何其他进程的东西,所以我们可以在 vagrant 文件中执行类似的操作-

    VAGRANT_COMMAND = ARGV[0]
    if VAGRANT_COMMAND == "ssh"
        config.ssh.extra_args = ["-t", "cd /vagrant; bash --login"]
    end
于 2020-02-02T01:21:03.123 回答