In Go, running CLI commands can be achieved using the os/exec package. This package provides functionality for executing and managing external commands. By using the exec.Command function, we can create an instance of the *exec.Cmd struct to represent an external command. We can then use methods such as Run, Start, or Output to execute the command.
Steps and Examples
-
Import the
os/execpackageAt the beginning of your Go file, import the necessary package.
goimport "os/exec" -
Create the command
Use the
exec.Commandfunction to create the command. This function accepts the command name and parameters as input.gocmd := exec.Command("echo", "Hello, World!") -
Run the command
Use the
Runmethod to execute the command. This will block until the command completes.goerr := cmd.Run() if err != nil { log.Fatalf("cmd.Run() failed with %s\n", err) }To capture the command's output, use the
Outputmethod:gooutput, err := cmd.Output() if err != nil { log.Fatal(err) } fmt.Println(string(output))
Complete Example Code
The following is a complete example demonstrating how to run a simple echo command and print its output.
gopackage main import ( "fmt" "log" "os/exec" ) func main() { // Create the command cmd := exec.Command("echo", "Hello, World!") // Run the command and capture the output output, err := cmd.Output() if err != nil { log.Fatal(err) } // Print the command's output fmt.Println(string(output)) }
Running the above program will output:
shellHello, World!
This example demonstrates how to run CLI commands in Go and handle their output. Using similar methods, you can run different CLI commands and handle the output or errors as needed.