In this scenario, you aim to execute system commands that resemble appending content to a file. However, when the command exceeds a single word, your program encounters errors.
Identifying the Issue
The initial code attempts to execute the command directly, failing to distinguish between the command and its arguments. This is problematic when the command comprises multiple words.
Solution
One way to address this is by leveraging the Shell as an intermediary, as seen in the proposed solution:
out, err := exec.Command("sh", "-c", cmd).Output()
The -c flag instructs the Shell to interpret cmd as a command, allowing the program to specify both the command and its arguments separately.
Alternative and Efficient Approach
A more efficient and straightforward approach utilizes Go's variadic arguments:
func exeCmd(cmd string, wg *sync.WaitGroup) { parts := strings.Fields(cmd) head := parts[0] parts = parts[1:len(parts)] out, err := exec.Command(head, parts...).Output() }
In this approach, the command is split into its head (the primary command) and a slice containing the remaining arguments. The head and parts are then passed as arguments to exec.Command.
The above is the detailed content of How Can I Correctly Execute Multi-Word System Commands in Go?. For more information, please follow other related articles on the PHP Chinese website!