Home > Backend Development > Golang > How to Safely Execute System Commands with Variable Arguments in Go?

How to Safely Execute System Commands with Variable Arguments in Go?

DDD
Release: 2024-12-13 08:00:19
Original
331 people have browsed it

How to Safely Execute System Commands with Variable Arguments in Go?

Executing System Commands with Variable Arguments

When executing system commands that involve multiple arguments, it becomes necessary to separate the command from the arguments. The code below illustrates this concept:

import (
    "fmt"
    "os/exec"
    "strings"
    "sync"
)

func exeCmd(cmd string, wg *sync.WaitGroup) {
    fmt.Println("command is ", cmd)
    // Splitting head (e.g., "g++") from the rest of the command (e.g., "-c file.cpp")
    parts := strings.Fields(cmd)
    head := parts[0]
    parts = parts[1:len(parts)]

    out, err := exec.Command(head, parts...).Output()
    if err != nil {
        fmt.Printf("%s", err)
    }
    fmt.Printf("%s", out)
    wg.Done() // Signal to waitgroup that this goroutine is done
}

func main() {
    wg := new(sync.WaitGroup)
    wg.Add(3)

    x := []string{
        "echo newline >> foo.o",
        "echo newline >> f1.o",
        "echo newline >> f2.o"}

    go exeCmd(x[0], wg)
    go exeCmd(x[1], wg)
    go exeCmd(x[2], wg)

    wg.Wait()
}
Copy after login

In this code:

  • exec.Command(head, parts...) separates the command from the arguments using Go's variadic arguments.
  • The head variable contains the system command (e.g., "echo").
  • The parts variable contains the remaining arguments (e.g., "newline >> foo.o").
  • The strings.Fields(cmd) function is used to split the command into its constituent parts.

Using this approach, the program can execute system commands with an arbitrary number of arguments. It overcomes the limitation of the original code, which failed for commands with multiple words.

The above is the detailed content of How to Safely Execute System Commands with Variable Arguments in Go?. 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