Executing Windows Commands in Golang
When attempting to execute a basic Windows command using exec.Command("del", "c:\aaa.txt"), you may encounter an error stating that the executable was not found in the path. This is because commands like del are built into the Windows command prompt and do not have standalone executable files.
To resolve this, you can use the cmd command to execute these commands:
package main import ( "fmt" "os/exec" ) 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 uses the appropriate command. For Windows, it executes the command through cmd, while for other systems it uses the rm command directly.
The above is the detailed content of How to Execute Built-in Windows Commands (like `del`) in Golang?. For more information, please follow other related articles on the PHP Chinese website!