Home >Backend Development >Golang >Why Does `exec.Command('del', ...) ` Fail in Golang on Windows, and How Can I Fix It?
Executing Windows Commands in Golang: Troubleshooting 'del' Executable Not Found Error
Your attempt to execute the "del" command using exec.Command("del", "c:\aaa.txt") within Golang resulted in an error message indicating that the executable file was not found in the system path.
Unlike other operating systems, Windows has built-in commands that are not available as standalone executables. These commands are executed through the Command Prompt (cmd.exe). To execute these commands in Golang, you need to use the "cmd /c" prefix.
The following code snippet demonstrates how to correctly execute the "del" command in Windows using Golang:
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) } }
In this code snippet:
This code will correctly execute the "del" command in Windows and delete the specified file, whereas the previous attempt to directly execute "del" would fail.
The above is the detailed content of Why Does `exec.Command('del', ...) ` Fail in Golang on Windows, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!