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

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

在 Go 中執行帶有參數的命令?

在 Go 中執行帶有參數的命令?

Go
波斯汪 2023-06-19 15:58:17
在我的 shell 中,我可以執行命令acme.sh --issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please并獲取輸出?,F在我想這樣做,我的代碼如下:cmd := exec.Command("bash", "-c", "acme.sh --issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please");out, err := cmd.CombinedOutput()if err != nil {    log.Fatalf("issue failed with error: %s\n", err)}fmt.Printf("combined out:\n%s\n", string(out))但我得到了錯誤exit status 1。正如評論所說,我將論點分開:exec.Command("bash", "-c", "acme.sh", "--issue", "--dns", "-d exmaple.com", "--yes-I-know-dns-manual-mode-enough-go-ahead-please");but the result is that it exec acme.sh without parameters.
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

使用此腳本作為 acme.sh


#!/bin/bash


echo "$*"

使用同一目錄中給出的程序會發生您報告的錯誤


但是,如果我將當前目錄添加到 shell PATH


export PATH=.:$PATH

然后程序按預期執行,就我的版本而言


$ go run c.go?

combined out:

--issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please

好的,這就是 bash -c 將單個字符串作為命令的情況(稍后會詳細介紹)


如果命令是這樣發出的


? ? cmd := exec.Command("acme.sh", "--issue", "--dns", "-d exmaple.com", "--

yes-I-know-dns-manual-mode-enough-go-ahead-please")

然后,當稍后對您的問題狀態進行編輯時,命令 acme.sh 將在沒有參數的情況下運行。


問題在于行為方式bash -c。


從手冊頁


bash 在調用時解釋以下選項:


? ?-c? ? ? ? If the -c option is present, then commands are read from? the

? ? ? ? ? ? ?first non-option argument command_string.? If there are argu‐

? ? ? ? ? ? ?ments after the command_string,? they? are? assigned? to? the

? ? ? ? ? ? ?positional parameters, starting with $0.

在您的情況下,這意味著第一個參數bash -c被接受為命令。其他參數丟失,因為它們是新 bash shell 而不是命令的位置acme.sh參數

,確保腳本有正確的 bang 行并依賴內核 binfmt 處理程序


查看完整回答
反對 回復 2023-06-19
?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

從 err 中排除exit status 1將得到正確的結果。


cmd := exec.Command("bash", "-c", "acme.sh --issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please");

out, err := cmd.CombinedOutput()

if err != nil && err.Error() != "exit status 1" {

    log.Fatalf("issue failed with error: %s\n", err)

}

fmt.Printf("combined out:\n%s\n", string(out))


查看完整回答
反對 回復 2023-06-19
  • 2 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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