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

How to Execute Built-in Windows Commands (like `del`) in Golang?

DDD
DDDOriginal
2024-12-14 02:54:09672browse

How to Execute Built-in Windows Commands (like `del`) in Golang?

Executing Windows Commands in Golang

When attempting to execute a basic Windows command using exec.Command("del", "c:\aaa.txt"), you may encounter an error stating that the executable was not found in the path. This is because commands like del are built into the Windows command prompt and do not have standalone executable files.

To resolve this, you can use the cmd command to execute these commands:

package main

import (
    "fmt"
    "os/exec"
)

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)
    }
}

This code checks the operating system and uses the appropriate command. For Windows, it executes the command through cmd, while for other systems it uses the rm command directly.

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

Statement:
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