golang一键打包macos, linux, windows 应用程序 shell脚本

golang一键打包各个平台可执行应用程序shell脚本, 可自定义输出文件名,自动一键打包3大平台可执行应用程序。废话不多说,直接上代码:

bash 复制代码
#!/bin/sh
##################################
# 生成各个平台下的可执行程序 golang一键打包 macos, linux, windows 应用程序
# 使用方法: sh build.sh [-n appname]
# 也可忽略 -n 参数 sh build.sh  默认名称为 myapp
#
# 如: sh build.sh -n helloworld 将自动在target目录下生成以下3个可执行文件
# helloworld-darwin-amd64.bin  helloworld-linux-amd64.bin helloworld-windows-amd64.exe
#
# Author: tekintian@gmail.com
##################################

# 获取用户输入参数
while getopts ":n:" opt; do
    case $opt in
    n)
        APPNAME=$OPTARG
        ;;
    ?)
        echo "Unknown parameter"
        exit 1
        ;;
    esac
done

# -n yourappname  default app name is  myapp
APPNAME=${APPNAME:-"myapp"}
# 通用变量
export CGO_ENABLED=0 # 关闭CGO
export GOARCH=amd64  #CPU架构
# 设置darwin
export GOOS=darwin
go build -ldflags "-s -w" -o target/${APPNAME}-darwin-amd64.bin
echo "Macos可执行程序 ${APPNAME}-darwin-amd64.bin 打包成功!"
# 设置linux
export GOOS=linux
go build -ldflags "-s -w" -o target/${APPNAME}-linux-amd64.bin
echo "linux可执行程序 ${APPNAME}-linux-amd64.bin 打包成功!"
# 设置windows
export GOOS=windows
go build -ldflags "-s -w" -o target/${APPNAME}-windows-amd64.exe
echo "Windows可执行程序 ${APPNAME}-windows-amd64.exe 打包成功!"

保存以上代码到你的项目跟目录,如 build.sh 然后执行

bash 复制代码
sh build.sh -n helloworld 

在target目录下就会生成以下3个可执行文件

helloworld-darwin-amd64.bin

helloworld-linux-amd64.bin

helloworld-windows-amd64.exe

注意,如果你直接使用 go env 的方式先设置环境变量后再打包,必须要记着打包完成后要设置回你当前的环境变量,否则你的代码将无法运行, 如:

bash 复制代码
# mac平台编译linux
go env -w CGO_ENABLED=0 GOOS=linux GOARCH=amd64
go build

#切换回mac 
go env -w CGO_ENABLED=1 GOOS=darwin GOARCH=amd64

本文介绍的工具 build.sh 不会有这个烦恼, 不用切换环境,不会影响你当前的golang运行环境!!!

相关推荐
计算机安禾4 分钟前
【Linux从入门到精通】第31篇:防火墙漫谈——iptables与firewalld防护指南
linux·运维·php
下一页盛夏花开21 分钟前
ubuntu 20中安装QT以后出现红色空心断点
linux·运维·ubuntu
sanshanjianke1 小时前
Thunderobot 911ME 笔记本 Linux 风扇控制研究
linux
开发者联盟league1 小时前
在windows上安装和运行rocketmq
windows·rocketmq
非凡ghost3 小时前
可拓浏览器:给手机浏览器装上“外挂“!2W+拓展+AI搜索,玩出无限可能!
windows·智能手机·音视频·firefox
fengyehongWorld4 小时前
TeraTerm ttl脚本登录wsl
linux·teraterm
小神.Chen4 小时前
如何删除远程桌面的连接记录,一键清理mstsc远程桌面连接的记录
windows
John_ToDebug4 小时前
WebHostView 与 TabStrip 交互机制深度解析
c++·chrome·windows
乌托邦的逃亡者4 小时前
Linux中如何检测IP冲突
linux·运维·tcp/ip
一曦的后花园5 小时前
linux搭建promethes并对接node-exporter指标
linux·运维·服务器