Home > Software design >  Golang exec.Command error on Windows due to double quote
Golang exec.Command error on Windows due to double quote

Time:12-15

I have this comment, which downloads a simple file:

var tarMode = "xf"
cmdEnsure = *exec.Command("cmd", "/C", fmt.Sprintf(`curl -L -o file.zip "https://drive.google.com/uc?export=download&id=theIDofthefile" && tar -%s file.zip`, tarMode))
err := cmdEnsure.Run()

This code in go will error because: curl: (1) Protocol ""https" not supported or disabled in libcurl.

Now I understand that this happends due to my double quote. However, if I remove if, I get the Id is not recognized as an internal or external command, operable program or batch file, which makes sense because the & simple means doing another command in cmd.

So what are my options for executing such download command and extract. The command itself run fine on cmd.

CodePudding user response:

I find it best to not try and combine multiple commands in one execution. The below works just fine and you don't have to worry about escaping and portability, you also get better error handling.

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    if b, err := exec.Command("curl", "-L", "-o", "file.zip", "https://drive.google.com/uc?export=download&id=theIDofthefile").CombinedOutput(); err != nil {
        fmt.Printf("% v, %v", string(b), err)
        return
    }

    if b, err := exec.Command("tar", "-x", "-f", "file.zip").CombinedOutput(); err != nil {
        fmt.Printf("% v, %v", string(b), err)
    }
}
  • Related