Solving Execution of System Commands with Variable Arguments
In many scenarios, it's common to encounter system commands that require variable numbers of arguments. However, executing such commands in a simple script can pose a challenge when attempting to execute commands beyond basic single-word commands.
In a sample Go script presented earlier, attempts to execute commands like echo newline >> foo.o resulted in errors, indicating that the script failed to recognize the commands. This is likely due to a lack of separation between the command and its arguments in the execution process.
Subverting the Issue using "sh"
One solution found to bypass this limitation involves the use of sh (shell) command:
out, err := exec.Command("sh", "-c", cmd).Output()
A Simplified and Efficient Approach
A better alternative that leverages Go's variadic argument support is the following:
func exeCmd(cmd string, wg *sync.WaitGroup) { // Split command into head and parts 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) }
This solution takes advantage of variadic arguments in Go, allowing you to pass a variable number of arguments to the command. The head variable represents the command itself, while parts holds the rest of the arguments. By utilizing variadic arguments, the need for external commands like sh is eliminated, resulting in a more efficient and straightforward execution process.
The above is the detailed content of How to Efficiently Execute System Commands with Variable Arguments in Go?. For more information, please follow other related articles on the PHP Chinese website!