test.go
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("指令行參數有:", len(os.Args))
for i, v := range os.Args {
fmt.Printf("args[%v]=%v\n", i, v)
}
}
linux執行指令編譯可執行檔案:
go build -o test test.go
執行指令:
./test a b c 1 2
windows 執行指令編譯可執行檔案:
go build -o test.exe test.go
執行指令:
test.exe a b c 1 2
輸出:
指令行參數有: 6
args[0]=./test
args[1]=a
args[2]=b
args[3]=c
args[4]=1
args[5]=2
flag解析指令行參數
test.go
package main
import (
"flag"
"fmt"
)
func main() {
// 定義變量用來接收指令行參數
var user string
var pwd string
var host string
var port int
//&user 接收使用者指令行中輸入的 -u 後面的參數值
//"u" 用 -u 指定參數
//"" 定義預設值
//"使用者名,預設為空" 參數的相關說明
flag.StringVar(&user, "u", "", "使用者名,預設為空")
flag.StringVar(&pwd, "pwd", "", "密碼,預設為空")
flag.StringVar(&host, "h", "localhost", "主機名,預設為localhost")
flag.IntVar(&port, "p", 3306, "端口号,預設為3306")
//必須調用此方法才能生效
flag.Parse()
fmt.Printf("user=%v, pwd=%v, host=%v, port=%v\n",
user, pwd, host, port)
}
編譯可執行檔案
linux執行指令編譯可執行檔案:
go build -o test test.go
執行指令:
./test -u root -pwd 123 -h 127.0.0.1
windows 執行指令編譯可執行檔案:
go build -o test.exe test.go
執行指令:
test.exe -u root -pwd 123 -h 127.0.0.1
輸出:
user=root, pwd=123, host=127.0.0.1, port=3306
如果輸入的指令錯誤,如:
./test -u root -pwd 123 -h 127.0.0.1 -kk
則輸出:
flag provided but not defined: -kk
Usage of ./test:
-h string
主機名,預設為localhost (default "localhost")
-p int
端口号,預設為3306 (default 3306)
-pwd string
密碼,預設為空
-u string
使用者名,預設為空