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?

Linda Hamilton
Release: 2024-12-24 17:43:10
Original
1014 people have browsed it

How to Execute Built-in Windows Commands Like

Executing Windows Commands in Golang

When attempting to execute a simple Windows command such as "del c:aaa.txt" using "exec.Command", users may encounter an error indicating that the executable file cannot be found in the system path. This error occurs because certain commands, like "del," are built into the Windows command interpreter (cmd.exe) and do not have standalone executable files.

Solution

To execute these built-in commands in Golang, the following approach can be taken:

  1. Cross-Platform Handling: Check the current operating system using runtime.GOOS.
  2. Windows: For Windows systems, use exec.Command("cmd", "/C", command) to run the desired command through the command interpreter.
  3. Mac/Linux: For Mac and Linux systems, execute the command directly using exec.Command("command").

Here's a modified code snippet that incorporates this solution:

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:
        c = exec.Command("rm", "-f", "D:\a.txt")
    }

    if err := c.Run(); err != nil {
        fmt.Println("Error:", err)
    }
}
Copy after login

Using this approach, you will be able to execute Windows built-in commands successfully in Golang, even those without standalone executable files.

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