In Go, the os/exec
package provides functionality for executing external commands. This allows you to run shell commands and interact with the command’s standard input, output, and error streams.
Using os/exec
To use the os/exec
package, you first need to import it in your Go code:
import "os/exec"
Running a Command
You can execute a command using the Command
function from the os/exec
package:
cmd := exec.Command("ls", "-l")
In this example, we’re running the ls -l
command.
Handling Output
To capture the output of the command, you can use the Output
function:
output, err := cmd.Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(output))
This code captures the output of the command and prints it to the console.
Handling Input
You can also provide input to the command’s standard input stream:
cmd := exec.Command("cat")
stdin, _ := cmd.StdinPipe()
io.WriteString(stdin, "Hello, World!")
stdin.Close()
output, _ := cmd.CombinedOutput()
fmt.Println(string(output))
In this example, we use the StdinPipe
function to get a pipe to the standard input stream of the command and write to it using io.WriteString
.
Conclusion
The os/exec
package in Go provides a powerful and flexible way to execute external commands and interact with them. It is a useful tool for building command-line interfaces and interacting with other system processes.
For more detailed information, you can refer to the official documentation.
Now you have a good understanding of how to use os/exec
in Go to execute external commands, handle their input and output, and work with the standard streams.