I'm trying to call a built in command for the command prompt and I'm getting errors I don't understand.
func main() {
cmd := exec.Command("del", "C:\trial\now.txt")
// Reboot if needed
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
And I'm getting the following error:
exec: "del": executable file not found in %PATH%
exit status 1
What am I doing wrong?
del is not an executable, it's a built-in command. exec.Command allows you to fork out to another executable. To use shell commands, you would have to call the shell executable, and pass in the built-in command (and parameters) you want executed:
cmd := exec.Command("cmd.exe", "/C", "del C:\\trial\\now.txt")
Note that you also have to escape backslashes in strings as above, or use backtick-quoted strings:
cmd := exec.Command("cmd.exe", "/C", `del C:\trial\now.txt`)
However, if you just want to delete a file, you're probably better off using os.Remove to directly delete a file rather than forking out to the shell to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With