我指的是如何使用未知參數執行系統命令?在我的 ubuntu shell 上運行 jq 命令。下面是我試過的代碼import ( "fmt" "os/exec" "sync" "strings")func exeCmd(cmd string, wg *sync.WaitGroup) { fmt.Println("command is ",cmd) // splitting head => g++ parts => rest of the command parts := strings.Fields(cmd) head := parts[0] parts = parts[1:len(parts)] out, err := exec.Command(head,parts...).Output() if err != nil { fmt.Printf("%s", err) } fmt.Printf("%s", out) wg.Done() // Need to signal to waitgroup that this goroutine is done }func main() { wg := new(sync.WaitGroup) wg.Add(1) x := []string{"jq '(.data.legacyCollection.collectionsPage.stream.edges|map({node:(.node|{url,firstPublished,headline:{default:.headline.default},summary})})) as $edges|{data:{legacyCollection:{collectionsPage:{stream:{$edges}}}}}' long-response.json > short-response.json"} exeCmd(x[0], wg) wg.Wait()}輸出如下,似乎命令被正確檢測到,但 shell 返回退出狀態 3,即“沒有這樣的過程”?command is jq '(.data.legacyCollection.collectionsPage.stream.edges|map({node:(.node|{url,firstPublished,headline:{default:.headline.default},summary})})) as $edges|{data:{legacyCollection:{collectionsPage:{stream:{$edges}}}}}' long-response.json > short-repsonse.json exit status 3任何人都可以幫忙嗎?我想要的是一個 go 函數,它可以像在 Linux shell 上一樣包裝和運行 bash 命令行嘗試了其他方法:刪除了我的 jq 命令中的單引號,我的命令得到了我期望的輸出執行 - 一個解析的 json 文件但是,我仍然有一個存在狀態 2,任何人都可以解釋為什么我的命令行中的單引號會影響 G 解析命令的方式?為什么在我的 shell 命令完成后我仍然存在 2?
1 回答

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
該程序執行 jq 命令,而不是 shell。jq 命令不理解傳遞給命令的 shell 語法(引號和 I/O 重定向)。
使用以下代碼運行命令,標準輸出重定向到 short-response.json。
cmd := exec.Command("jq",
"(.data.legacyCollection.collectionsPage.stream.edges|map({node:(.node|{url,firstPublished,headline:{default:.headline.default},summary})})) as $edges|{data:{legacyCollection:{collectionsPage:{stream:{$edges}}}}}",
"long-response.json")
f, err := os.Create("short-response.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
cmd.Stdout = f // set stdout to short-response.json
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
- 1 回答
- 0 關注
- 216 瀏覽
添加回答
舉報
0/150
提交
取消