使用golang编写shell脚本
# 1. 准备工作
前提:默认读者已准备好Golang的开发环境
# 1.1 获取最新cobra依赖包
go get -u github.com/spf13/cobra
# 1.2 install cobra
# 进入目录: %GOPATH%/pkg/mod/github.com/spf13/cobra@version/cobra
# install cobra
go install
# 结束检查目录:%GOPATH%/bin, 存在产物cobra.exe/cobra则表示成功
# 2. 创建shell脚本golang工程
# 2.1 初始化golang工程
mkdir app
cd app
app> go mod init app
# 2.2 初始化cobra
command: app> cobra init --pkg-name app
result: Your Cobra application is ready at
此时,你的工程目录是这样:
此时,工程并不能直接run,需要优化import:
app> go mod tidy
使用goland的读者,可以直接在go.mod文件上右键,执行Go Mod Tidy
注意:viper
依赖包国内可能无法下载,需要在go.mod文件中使用replace
替换为github.com上的包。
# 2.3 添加自定义命令
在上一步中,我们已经初始化了根命令,但目前还不能正式使用,也不能实现我们自己的业务逻辑,需要添加子命令。
# 2.3.1 添加自定义命令
譬如,我们要实现app serve
、app config
之类的命令,那么可以进行如下操作:
app> cobra add serve
app> cobra add config
执行上述命令后,就会生成两个子命令,此时工程代码为:
这时,工程已经能够运行起来了:
app> go run main.go
结果:
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
app [command]
Available Commands:
completion generate the autocompletion script for the specified shell
config A brief description of your command
help Help about any command
serve A brief description of your command
Flags:
--config string config file (default is $HOME/.app.yaml)
-h, --help help for app
-t, --toggle Help message for toggle
Use "app [command] --help" for more information about a command.
执行子命令:
command: app> go run main.go serve
result: serve called
# 2.3.2 添加子命令
如果要对app config
命令添加子命令create
,可以如下操作:
app> cobra add create -p configCmd
完成后,会在cmd目录下生成create.go文件,其中configCmd
是父命令的变量名,一般就是在命令的后面加上Cmd
。
至此,你已经有了一个shell脚本的命令框架了,只需要在其中填充业务逻辑代码即可。
# 2.4 测试命令
# 2.4.1 install命令
app> go install
命令执行后,会在 %GOPATH%/bin 目录下生成产物app.exe/app。
如果想在任意地方执行命令,请将%GOPATH%/bin目录添加到Path环境变量中。
# 2.4.2 执行命令
app> app serve
server called
app> app config
config called
app> app config create
create called
我们可以看到,命令执行完都会打印相关命令被call,至此基本框架算是完成了,只需要填充业务逻辑即可。
编辑 (opens new window)
上次更新: 2022/01/08, 23:34:06