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
Release: 2024-12-14 02:54:09
Original
590 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template