Calling Command with Arguments: Console Success, Terminal Failure
In this scenario, a Go program successfully executes the top command with two arguments (-n 10 and -l 2), displaying details of 10 processes. However, adding an additional argument (-o cpu) causes an error: "invalid argument -o".
The Problem
The error occurs when attempting to execute the top command from the terminal with the full argument list (-o cpu -n 10 -l 2). However, the same command works as expected when executed from the console.
The Root Cause
The issue stems from the way the arguments are parsed by the operating system. Normally, when commands are executed from the console, each argument is separated by a space. However, in the Go program, the arguments are being passed as a single string. This leaves the operating system to interpret the arguments, which it does incorrectly in this case.
The Solution
To resolve the issue, the arguments must be passed as separate strings to the exec.Command function. The following code demonstrates the correct way to do this:
import ( "os/exec" ) func main() { app := "/usr/bin/top" cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2") out, err := cmd.CombinedOutput() // Error handling omitted for brevity value := string(out) return value }
By passing each argument as a separate string, the operating system can correctly interpret the command and execute it as intended. This resolves the error and allows the program to successfully display details of 10 processes with the additional argument (-o cpu).
The above is the detailed content of Why Does My Go Program's `exec.Command` Fail in the Terminal But Succeed in the Console?. For more information, please follow other related articles on the PHP Chinese website!