Golang中Bash命令未执行的解决方法

Golang中Bash命令未执行的解决方法 我尝试在 Core OS 上使用 Golang 执行以下命令:

/bin/xargs -0 bash -c 'printf "%q\n" "$@"' -- < /proc/3194/environ

但执行失败,退出状态为 127,错误信息为:“bash: printf “%!q(MISSING)\n” “$@”: command not found\n”

subcmd := fmt.Sprintf("%s %s", "'printf \"%%q\\n\" \"$@\"' -- &lt; ", file)

cmd := exec.Command("xargs", "-0", "bash", "-c", subcmd)

out, err := cmd.CombinedOutput()

更多关于Golang中Bash命令未执行的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

在shell中有效的等效命令是什么?

更多关于Golang中Bash命令未执行的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


/bin/xargs -0 bash -c ‘printf “%q\n” “$@”’ – < /proc/3194/environ

/bin/xargs -0 bash -c 'printf "%q\n" "$@"' -- < /proc/3194/environ

问题在于你构建子命令字符串的方式。bash -c 期望接收一个完整的命令字符串,但你的字符串拼接方式导致了参数解析错误。以下是正确的实现方法:

package main

import (
    "fmt"
    "os/exec"
    "log"
)

func main() {
    pid := "3194"
    file := fmt.Sprintf("/proc/%s/environ", pid)
    
    // 正确的方式:将整个bash命令作为单个字符串传递
    bashCmd := fmt.Sprintf("printf %%q\\n \"$@\" < %s", file)
    
    cmd := exec.Command("xargs", "-0", "bash", "-c", bashCmd, "--")
    
    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatalf("命令执行失败: %v\n输出: %s", err, out)
    }
    
    fmt.Printf("输出:\n%s", out)
}

或者更简洁的版本,直接使用bash执行:

package main

import (
    "os/exec"
    "log"
    "fmt"
)

func main() {
    pid := "3194"
    
    cmd := exec.Command("bash", "-c", 
        "xargs -0 bash -c 'printf \"%q\\n\" \"$@\"' -- < /proc/"+pid+"/environ")
    
    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatalf("命令执行失败: %v\n输出: %s", err, out)
    }
    
    fmt.Printf("输出:\n%s", out)
}

关键点:

  1. bash -c 后面的参数应该是一个完整的命令字符串
  2. 使用 -- 作为分隔符来传递后续参数
  3. 避免在字符串中转义时引入额外的引号问题

如果仍然遇到问题,可以尝试使用 CommandContext 并检查环境变量:

package main

import (
    "context"
    "os/exec"
    "log"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    pid := "3194"
    cmd := exec.CommandContext(ctx, "bash", "-c",
        "xargs -0 bash -c 'for arg; do printf \"%q\\n\" \"$arg\"; done' -- < /proc/"+pid+"/environ")
    
    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatalf("命令执行失败: %v\n输出: %s", err, out)
    }
    
    fmt.Printf("输出:\n%s", out)
}

这些示例应该能解决你的bash命令执行问题。

回到顶部