Home >Backend Development >Golang >Why Does My Go `exec.Command` Fail with Certain Arguments, While the Same Command Works in the Console?
Calling Commands with Arguments: Troubleshooting Errors
When attempting to execute a command with arguments using the exec.Command function in Go, developers may encounter inconsistencies where certain arguments are accepted while others are met with errors.
One such example is the following code:
package main import ( "os/exec" ) func main() { print(top()) } func top() string { app := "/usr/bin/top" cmd := exec.Command(app, "-n 10", "-l 2") out, err := cmd.CombinedOutput() if err != nil { return err.Error() + " " + string(out) } value := string(out) return value }
This code successfully outputs the details of 10 processes. However, adding an additional argument of "-o cpu" (e.g., cmd := exec.Command(app, "-o cpu", "-n 10", "-l 2")) results in the following error:
exit status 1 invalid argument -o: cpu /usr/bin/top usage: /usr/bin/top [-a | -d | -e | -c <mode>] [-F | -f] [-h] [-i <interval>] [-l <samples>] [-ncols <columns>] [-o <key>] [-O <secondaryKey>] [-R | -r] [-S] [-s <delay>] [-n <nprocs>] [-stats <key(s)>] [-pid <processid>] [-user <username>] [-U <username>] [-u]
This error occurs despite the fact that the command "top -o cpu -n 10 -l 2" works in the console.
Solution:
The key to resolving this issue is to separate the arguments. In a shell, commands and arguments are typically separated by spaces. However, when using exec.Command, each argument must be passed as a separate string:
exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
By passing arguments this way, the program correctly interprets the command and its arguments. This prevents the error that arises when arguments are combined into a single string (e.g., "-o cpu").
The above is the detailed content of Why Does My Go `exec.Command` Fail with Certain Arguments, While the Same Command Works in the Console?. For more information, please follow other related articles on the PHP Chinese website!