How to deal with quoted and unquotes strings when executing it in command prompt?

Issue


input comes from an JSON request which looks like

{ 
   "inputString" : "\"C:\\Program Files (x86)\\7-Zip\\7z.exe\" x c:\\temp\\test.zip -oc:\\temp\\test" 
}

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    //Input received will be of this format
    var inputstring string = "\"C:\Program Files (x86)\7-Zip\7z.exe\" x c:\temp\firmware8.zip -oc:\temp\fw"

    cmd := exec.Command("cmd", "/c", inputstring)

    out, err := cmd.Output()

    fmt.Println("doneee", string(out), "err", err)
}

Output : "’\"C:\Program Files (x86)\7-Zip\7z.exe\
"’
is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"

"C:\Program Files (x86)\7-Zip\7z.exe" x c:\temp\test.zip -oc:\temp\test – I have to run this command on command prompt but it is just executing the part which is highlighted

As the input string is not static (it comes from a JSON),So we cannot split them into arguments

Solution

var inputstring string = "\"C:\\Program Files (x86)\\7-Zip\\7z.exe\" x c:\\temp\\firmware8.zip -oc:\\temp\\fw"
var buf, stderr bytes.Buffer
*proc := exec.Command("cmd")
proc.SysProcAttr = &syscall.SysProcAttr{CmdLine: fmt.Sprintf(`/c "%s"`, inputstring)}* //Adding this line helped to add the cmd as single line

proc.Stderr = &stderr
proc.Stdout = &buf
proc.Start()
time.Sleep(5 * time.Second)
fmt.Println("doneee", buf.String(), "error is ", stderr.String())

Answered By – meena sushanth

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.