Golang中命令行参数Os.args和带引号字符串的处理方案
Golang中命令行参数Os.args和带引号字符串的处理方案 环境: 操作系统:Linux Fedora 38 Go 版本:1.20.6
代码片段:
for e := 0; e < len(os.Args); e++ {
println(fmt.Sprintf("Args[%v]=%v", e, os.Args[e]))
}
命令行:
go run myprogram "xxx yyy"
结果:
Args[0]=/tmp/go-build176778176/b001/exe/myprogram
Args[1]=xxx
Args[2]=yyy
问题: CharGPT 告诉我使用双引号来包裹传递的短语。 https://chat.openai.com/share/7f7e4690-234f-4e4d-847f-88b90b13667a
结果应该是 Args[1] 包含整个被引用的短语,并且不应该有 Args[2]。我需要获取整个短语。 我哪里做错了?
更多关于Golang中命令行参数Os.args和带引号字符串的处理方案的实战教程也可以访问 https://www.itying.com/category-94-b0.html
……我回答了我的最后一个问题。
不要对 run 命令使用 -ldflags。它只适用于 build 和 install 命令。
更多关于Golang中命令行参数Os.args和带引号字符串的处理方案的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go中,os.Args的行为是由操作系统shell处理的,不是Go运行时。当你在shell中执行go run myprogram "xxx yyy"时,shell会在将参数传递给程序之前解析引号。你的代码实际上接收到的参数已经被shell分割了。
要验证这一点,可以尝试以下测试:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Number of args:", len(os.Args))
for i, arg := range os.Args {
fmt.Printf("Args[%d] = %q\n", i, arg)
}
}
运行方式:
go run test.go "xxx yyy"
你会看到输出:
Number of args: 2
Args[0] = "/tmp/go-build.../test"
Args[1] = "xxx yyy"
如果看到的是Args[1] = "xxx"和Args[2] = "yyy",那说明你的shell或执行环境有问题。可以尝试:
- 使用不同的shell:
bash -c 'go run test.go "xxx yyy"'
- 使用转义字符:
go run test.go \"xxx yyy\"
- 直接编译后运行:
go build -o test test.go
./test "xxx yyy"
- 使用
fmt.Sprintf格式化参数:
// 如果需要重新组合参数
if len(os.Args) > 1 {
fullArg := ""
for i := 1; i < len(os.Args); i++ {
if i > 1 {
fullArg += " "
}
fullArg += os.Args[i]
}
fmt.Printf("Combined argument: %q\n", fullArg)
}
如果问题仍然存在,检查你的shell配置或尝试在终端中直接运行:
printf '%s\n' "xxx yyy" | xargs go run test.go
这能确保参数被正确传递。

