我指的是如何使用未知引數執行系統命令?在我的 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 命令列 PS:我上面嘗試的 jq 命令在我將它粘貼到我的 Linux shell 上時效果很好
嘗試了其他方法:洗掉了我的 jq 命令中的單引號,并且我的命令得到了我期望的輸出執行 - 一個決議的 json 檔案,但我仍然有一個存在狀態 2 ,任何人都可以解釋
- 為什么我的命令列中的單引號會影響 G 決議命令的方式?
- 為什么我的 shell 命令完成后我仍然存在 2?
uj5u.com熱心網友回復:
該程式執行 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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/474149.html
標籤:去
