简体   繁体   中英

Golang exec.Command error on Windows due to double quote

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 .

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM