SoFunction
Updated on 2025-03-05

golang execution command line implementation

Generally speaking, if you execute some commands such as git clone in golang, you can use functions

func RunCommand(path, name string, arg ...string) (msg string, err error) {
    cmd := (name, arg...)
     = path
    err = ()
    ()
    if err != nil {
        ("err", (), "cmd", )
    }
    return
}

There is no problem with this writing, but if an execution error occurs, the return value will be too concise, for example

func main() {
    msg, err := ("./", "/bin/bash", "-c", "git clone url")
    if err != nil {
        (err)
        return
    }
    (msg)
}

After execution, return to exit status 128. This prompt is too abstract and needs to be viewed specifically at search engines. If you want to see more detailed reasons, this is still needed.

func RunCommand(path, name string, arg ...string) (msg string, err error) {
    cmd := (name, arg...)
    var out 
    var stderr 
     = &out
     = &stderr
     = path
    err = ()
    ()
    if err != nil {
        msg = (err) + ": " + ()
        err = (msg)
        ("err", (), "cmd", )
    }
    (())
    return
}

Execute again, return

2022/04/03 20:33:49 [/bin/bash -c git clone url]
2022/04/03 20:33:49 err exit status 128: fatal: repository 'url' does not exist
 cmd [/bin/bash -c git clone url]
2022/04/03 20:33:49 
2022/04/03 20:33:49 exit status 128: fatal: repository 'url' does not exist

Oh, it turns out that the reason for repository 'url' does not exist.

Let’s go further, why can you get the value by adding Stdout and Stderr? This is because some commands will hit the error message to Stdout, and some commands will hit the error message to Stderr, so you have to keep both.

refer to:How to debug “exit status 1” error when running in Golang

This is the end of this article about the implementation of golang execution command line. For more related golang execution command line content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!