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: [email protected]
##################################

# 获取用户输入参数
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运行环境!!!

相关推荐
Fanche4042 小时前
MySQL 8 自动安装脚本(CentOS-7 系统)
linux·运维·数据库·mysql·centos
zhishishe2 小时前
2025 年免费 Word 转 PDF 转换器有哪些?
android·windows·pdf·电脑·word
W_kiven3 小时前
Centos安装Dockers+Postgresql13+Postgis3.1
linux·运维·docker·postgresql·centos
liulilittle3 小时前
FTTR 全屋光纤架构分享
linux·服务器·网络·ip·通信·光纤·fttr
niuTaylor5 小时前
从入门到精通:CMakeLists.txt 完全指南
linux·服务器·cmake
我该如何取个名字7 小时前
Mac mini 安装mysql数据库以及出现的一些问题的解决方案
数据库·mysql·macos
SuperW8 小时前
Linux学习——UDP
linux·学习·udp
Xiaoyu Wang8 小时前
Go协程的调用与原理
开发语言·后端·golang
菜狗想要变强9 小时前
Linux驱动开发--异步通知与异步I/O
linux·运维·驱动开发
SuperW9 小时前
Linux学习——IO多路复用知识
linux·服务器·学习