Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executable files not in path - GO

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?

like image 272
brandonunited Avatar asked Jan 22 '26 12:01

brandonunited


1 Answers

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.

like image 108
Adrian Avatar answered Jan 24 '26 01:01

Adrian