Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a simple Windows command in Golang?

Tags:

windows

cmd

go

How to run a simple Windows command?

This command:

exec.Command("del", "c:\\aaa.txt") 

.. outputs this message:

del: executable file not found in %path%

What am I doing wrong?

like image 450
Yster Avatar asked Oct 22 '12 09:10

Yster


People also ask

What is cmd in Golang?

Overview. Package cmd runs external commands with concurrent access to output and status. It wraps the Go standard library os/exec. Command to correctly handle reading output (STDOUT and STDERR) while a command is running and killing a command. All operations are safe to call from multiple goroutines.

What is OS exec?

In computing, exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay.

How do I run a file in go?

To run a go program, create a file with an extension .go and write your golang code in that file. For example, we will create a file named helloworld.go and write the following code in it. Now open command prompt and navigate to the location of helloworld.go file.


1 Answers

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)     }    } 
like image 67
ANisus Avatar answered Sep 21 '22 17:09

ANisus