linux中用shell快速安装配置Go语言的开发环境
介绍
go1.5+版本提供编译好的安装包,我们只需要解压到相应的目录,并添加一些环境变量的配置即可。
Go语言的安装步骤
下载安装包go1.7.linux-amd64.tar.gz
解压文件到指定目录:tar-zxfgo1.7.linux-amd64.tar.gz
设置环境变量:GOROOT,GOPATH,PATH
既然我们可以列出这些步骤,那么便可以将整个过程自动化。
下面是安装脚本
#!/bin/bash
#Upgradegoversionto1.7
#wgethttps://storage.googleapis.com/golang/go1.7.linux-amd64.tar.gzgo1.7.tar.gz
functioninfo(){
echo-e"\033[1;34m$1\033[0m"
}
functionwarn(){
echo-e"\033[0;33m$1\033[0m"
}
functionerror(){
echo-e"\033[0;31m$1\033[0m"
}
functionusage(){
info"Upgradeorinstallgolang..."
info"USAGE:"
info"./upgrade.shtar_filegopath"
info"tar_filespecifywhereisthetarfileofgobinaryfile"
info"gopathspecifywhereisthegoworkspace,includesrc,bin,pkgfolder"
}
functioncreateGoPath(){
if[!-d$1];
then
mkdir-p$1
fi
if[!-d"$1/src"];
then
mkdir"$1/src"
fi
if[!-d"$1/bin"];
then
mkdir"$1/bin"
fi
if[!-d"$1/pkg"];
then
mkdir"$1/pkg"
fi
}
if[-z$1];
then
usage
exit1
fi
file=$1
if[!-f$file];
then
error"${file}notexist..."
exit1
fi
unzipPath="`pwd`/tmp_unzip_path/"
info$unzipPath
if[!-d$unzipPath];
then
info"notexist"
mkdir$unzipPath
fi
tar-zxf$file-C$unzipPath
goroot=$GOROOT
if[!-n$GOROOT];
then
warn"Usedefaultgoroot/usr/local/go"
goroot="/usr/local/go"
fi
gopath=$2
info"Creategoworkspace,includesrc,bin,pkgfolder..."
if[-z$2];
then
user=`whoami`
gopath="/home/$user/workspace/golang"
warn"Use$gopathasgolangworkspace..."
if[!-d$gopath];
then
mkdir-p$gopath
fi
fi
createGoPath$gopath
info"Copygounzipfilesto$goroot"
sudocp-r"$unzipPath/go"$goroot
rm-rf$unzipPath
#etcProfile="/home/user/Desktop/etc"
etcProfile="/etc/profile"
exportGoroot="exportGOROOT=$goroot"
if[!-z$GOROOT];
then
cat$etcProfile|sed's/^export.GOROOT.*//'|sudotee$etcProfile>/dev/null
fi
echo$exportGoroot|sudotee-a$etcProfile
exportGopath="exportGOROOT=$gopath"
if[!-z$GOPATH];
then
cat$etcProfile|sed's/^export.GOPATH.*//'|sudotee$etcProfile>/dev/null
fi
echo"exportGOPATH=$gopath"|sudotee-a$etcProfile
echo'exportPATH=$GOROOT/bin:$GOPATH/bin:$PATH'|sudotee-a$etcProfile
###Replacemultipleemptylineswithoneemptyline
cat$etcProfile-s|sudotee$etcProfile>/dev/null
info"Tomakeconfigurationtakeeffect,willreboot,plsenter[y/n]"
read-p"[y/n]"isReboot
if[$isReboot="y"];
then
sudoreboot
fi
讲一讲脚本做的事情吧
1、脚本要求输入编译好的安装包,这里本来是可以做成直接下载的,但是考虑到大多数人是无法连接到golang的官网的,因此放弃了这一步。
2、解压文件到指定的目录,默认为/usr/local/go,也可以通过运行时指定
3、在GOPATH下面创建3个文件夹:src,bin,pkg,GOPATH可以运行时指定,默认为/home/{user}/workspace/golang
4、设置环境变量:$GOPATH,$GOROOT
5、重启服务,使对/etc/profile的修改生效
这里有一些主意的点是,有可能系统配置过golang的环境变量,那么需要先删除这些配置,然后重新写入。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。