Go语言(Golang)编写最简单的命令行工具"项目预览>echoabc123--name=nickabc123--name=nick课程概述如何制作命令行应用如何使用os.Args获得命令行参数前提条件懂得Go语言基本语法知识点OS包提供了用于处
>echo abc 123 --name=nick
abc 123 --name=nick
~/Code/go via 🐹 v1.20.3 via 🅒 base
➜ mcd echo # mkdir echo cd echo
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ c # code .
Code/go/echo via 🐹 v1.20.3 via 🅒 base took 2.4s
➜
main.go 文件
package main
import (
"fmt"
"os"
)
func main() {
var s, sep string
// os.Args
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
运行
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ go build .
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ ls
echo main.go
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ echo
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ echo 123
123
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ echo 123 abc ert
123 abc ert
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜
优化修改一
package main
import (
"fmt"
"os"
)
func main() {
// var s, sep string
s, sep := "", ""
// os.Args
for _, arg := range os.Args[1:] {
s += sep + arg
sep = " "
}
// for i := 1; i < len(os.Args); i++ {
// s += sep + os.Args[i]
// sep = " "
// }
fmt.Println(s)
}
运行
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜ go build . && echo 123 abc x=123ed
123 abc x=123ed
Code/go/echo via 🐹 v1.20.3 via 🅒 base
➜
优化修改二
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// var s, sep string
// s, sep := "", ""
// os.Args
// for _, arg := range os.Args[1:] {
// s += sep + arg
// sep = " "
// }
// for i := 1; i < len(os.Args); i++ {
// s += sep + os.Args[i]
// sep = " "
// }
// fmt.Println(s)
fmt.Println(strings.Join(os.Args[1:], " "))
}
实践
~/Code/go via 🐹 v1.20.3 via 🅒 base
➜ mcd cli-demo
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base
➜ go mod init
go: cannot determine module path for source directory /Users/qiaopengjun/Code/go/cli-demo (outside GOPATH, module path must be specified)
Example usage:
'go mod init example.com/m' to initialize a v0 or v1 module
'go mod init example.com/m/v2' to initialize a v2 module
Run 'go help mod init' for more information.
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base
➜ go mod init cli-demo
go: creating new go.mod: module cli-demo
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base
➜ c
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base
➜
main.go 代码
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println("What's your name?")
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
fmt.Printf("Your name is: %s", text)
}
运行
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base took 5.9s
➜ go run .
What's your name?
dave
Your name is: dave
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base took 3.1s
➜ go run main.go
What's your name?
xiaoqiao
Your name is: xiaoqiao
Code/go/cli-demo via 🐹 v1.20.3 via 🅒 base took 3.1s
➜
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!