Running Windows Commands from Golang
When attempting to execute a simple Windows command using exec.Command("del", "c:\aaa.txt"), you may encounter an error indicating that the executable file for the command is not found in the path.
The reason for this error is that Windows commands such as del are built into the cmd shell, and do not have their own stand-alone executable files. To execute these commands in Golang, you need to invoke the cmd shell and pass the command as an argument.
To resolve the issue, the following code snippet can be used:
package main import ( "fmt" "os/exec" "runtime" ) func main() { var c *exec.Cmd switch runtime.GOOS { case "windows": c = exec.Command("cmd", "/C", "del", "D:\a.txt") default: // Mac & Linux c = exec.Command("rm", "-f", "/d/a.txt") } if err := c.Run(); err != nil { fmt.Println("Error:", err) } }
This code checks the operating system and executes either the del command on Windows or the rm command on other operating systems, passing the desired file path as an argument.
The above is the detailed content of How to Execute Windows Commands (like `del`) from Golang?. For more information, please follow other related articles on the PHP Chinese website!