Vagrant - shell 配置程序无法设置 PATH 变量

Vagrant - shell 配置程序无法设置 PATH 变量

我想设置安装了 go 的 Ubuntu 18.04 VM。我有以下 shell 配置程序脚本:

wget https://dl.google.com/go/go1.15.5.linux-amd64.tar.gz
sudo tar -xzvf go1.15.5.linux-amd64.tar.gz
sudo mv /home/vagrant/go /usr/local

echo "export GOROOT=/usr/local/go" >> /home/vagrant/.bashrc
echo "export PATH=$GOROOT/bin:$PATH" >> /home/vagrant/.bashrc
source /home/vagrant/.bashrc

go version

但配置仍然失败,退出代码为非零。当我登录到 vagrant 用户帐户时,我已设置GOROOT,但PATH不包含/usr/local/go.

vagrant@vm:~$ echo $PATH
/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

vagrant@vm:~$ echo $GOROOT
/usr/local/go

vagrant@vm:~$ go

Command 'go' not found, but can be installed with:

snap install go         # version 1.15.6, or
apt  install golang-go
apt  install gccgo-go

See 'snap info go' for additional versions.

下载go是正确的,我的下有所有文件/usr/local/go

我有什么错吗?

答案1

您的问题源于使用双引号,它允许对变量进行插值。当你的 shell 脚本执行这一行时:

echo "export PATH=$GOROOT/bin:$PATH" >> /home/vagrant/.bashrc

GOROOT的价值在执行 shell 环境中为空,所以该命令的效果是:

echo "export PATH=/bin:$PATH" >> /home/vagrant/.bashrc

...这正是您所看到的:

vagrant@vm:~$ 回显 $PATH

/垃圾桶:...

^ here.

您希望将该代码逐字放入文件中,因此请使用单引号:

echo 'export GOROOT=/usr/local/go' >> /home/vagrant/.bashrc
echo 'export PATH=$GOROOT/bin:$PATH' >> /home/vagrant/.bashrc

相关内容