how to execute linux command in golang
To execute a Linux command in Go, you can use the os/exec
package, which provides functions for running external commands. Here are the steps to execute a Linux command in Go:
- Import the necessary packages:
import (
"fmt"
"os/exec"
)
- Define the command you want to execute:
command := exec.Command("ls", "-l")
In this example, we are executing the ls -l
command, which lists the files and directories in the current directory.
- Run the command and capture the output:
output, err := command.Output()
if err != nil {
fmt.Println("Error:", err)
return
}
The Output()
function runs the command and returns its output as a byte slice. If there is an error executing the command, it will be captured in the err
variable.
- Convert the output to a string and print it:
fmt.Println(string(output))
The string()
function converts the byte slice to a string, allowing us to print the output.
Here's the complete code:
package main
import (
"fmt"
"os/exec"
)
func main() {
command := exec.Command("ls", "-l")
output, err := command.Output()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(output))
}
This code will execute the ls -l
command and print the output. You can replace "ls"
and "-l"
with any other Linux command and its arguments to execute different commands.
Please note that the code assumes you have Go installed on your system and have set up the Go environment properly.