How to execute a simple Windows command in Golang?

I got the same error as you. But dystroy is correct: You can't run del or any other command built into cmd because there is no del.exe file (or any other del-executable for that matter).

I got it to work with:

package main

import(
    "fmt"
    "os/exec"
)

func main(){    
    c := exec.Command("cmd", "/C", "del", "D:\\a.txt")

    if err := c.Run(); err != nil { 
        fmt.Println("Error: ", err)
    }   
}

You need a Windows cmd to execute your dir command.

Try this :

cmd := exec.Command("cmd", "/C", "dir").Output()

(sorry, no Windows computer to check it right now)


In case you need the output of cmd:

if c, err := exec.Command("cmd","/c","del","a.txt").CombinedOutput(); err != nil {
        log.Fatal(err)
    } else {
        fmt.Printf("%s\n", c)
    }

Found another solution too. Create a batch file that contains the following: del c:\aaa.txt

Then call it like this:

exec.Command("c:\\del.bat").Run()

Tags:

Windows

Cmd

Go