Home >Backend Development >Golang >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() }
In this code:
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!