duanchandun1860 2015-03-15 22:05
浏览 20
已采纳

给定一个任意字符串,我如何将命令打包为bash?

I have a pretty basic golang question.

Given an arbitrary string like "echo foo", or "CGO_ENABLED=0 go build -o ./bin/echo -a main.go", what is the idiomatic way to parse/run that command using os/exec?

The way that I got this working seems pretty hacky, and I'm looking for a more idiomatic approach.

userInput = "CGO_ENABLED=0 go build -o ./bin/echo -a main.go"
command := exec.Command("/bin/bash", "-c", userInput)
out, err := command.Output()
if err != nil {
    fmt.Println(err)
 }
  • 写回答

2条回答 默认 最新

  • duanjia2772 2015-03-16 08:26
    关注

    Depending on how arbitrary and flexible your userInput string is, I might do something like this.

    package main
    
    import (
        "log"
        "os"
        "os/exec"
    )
    
    func main() {
        if err := os.Setenv("FOO", "bar"); err != nil {
            log.Println(err)
        }
    
        // As Dave C pointed out, exec.Command does this for you.
        // goAbsPath, err := exec.LookPath("go")
        // if err != nil {
        //   log.Println(err)
        // }
    
        // Pass whatever other arguments necessary.
        cmd := exec.Command("go", "version")
        if err = cmd.Run(); err != nil {
            log.Println(err)
        }
    }
    

    If nothing else, maybe os.Setenv and exec.LookPath might be useful to know about.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退