Reputation: 83
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?
Upvotes: 3
Views: 3828
Reputation: 46432
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.
Upvotes: 8
Reputation: 164799
In addition to the problem with the executable, your path string is not what you think it is.
cmd := exec.Command("del", "C:\trial\now.txt")
The \t
will be interpreted as a tab, and the \n
as a newline.
To avoid this, use ``
which has no special characters and no escape, not even \
. A great relief for Windows users!
cmd := exec.Command("del", `C:\trial\now.txt`)
See String Literals in the Go Language Spec for more.
Upvotes: 2