Home > Backend Development > Golang > How to Execute Windows Commands (like `del`) from Golang?

How to Execute Windows Commands (like `del`) from Golang?

Patricia Arquette
Release: 2024-12-08 12:04:14
Original
283 people have browsed it

How to Execute Windows Commands (like `del`) from Golang?

Running Windows Commands from Golang

When attempting to execute a simple Windows command using exec.Command("del", "c:\aaa.txt"), you may encounter an error indicating that the executable file for the command is not found in the path.

The reason for this error is that Windows commands such as del are built into the cmd shell, and do not have their own stand-alone executable files. To execute these commands in Golang, you need to invoke the cmd shell and pass the command as an argument.

To resolve the issue, the following code snippet can be used:

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)
    }
}
Copy after login

This code checks the operating system and executes either the del command on Windows or the rm command on other operating systems, passing the desired file path as an argument.

The above is the detailed content of How to Execute Windows Commands (like `del`) from Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template