亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 'exec.Command' 對待單引號參數特殊嗎?

Golang 'exec.Command' 對待單引號參數特殊嗎?

Go
慕勒3428872 2022-12-13 16:03:43
我指的是如何使用未知參數執行系統命令?在我的 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)

}


查看完整回答
反對 回復 2022-12-13
  • 1 回答
  • 0 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號