To execute external shell commands or processes using the os
package in Golang, you can use the os/exec
package. Here's an example:
package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func main() {
// Command to execute
cmd := exec.Command("ls", "-l")
// Set the command's output to os.Stdout
cmd.Stdout = os.Stdout
// Execute the command
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Println("Command executed successfully")
}
In this example, we execute the ls -l
command by creating an exec.Cmd
struct and setting its Stdout
field to os.Stdout
to redirect the command's output to the standard output. The cmd.Run()
function is used to execute the command.
If you want to capture the command's output, you can use the CombinedOutput()
function instead of Run()
. Here's an example:
package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func main() {
// Command to execute
cmd := exec.Command("ls", "-l")
// Execute the command and capture its output
output, err := cmd.CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
fmt.Println("Command executed successfully")
}
In this example, the CombinedOutput()
function is used to execute the command and capture its output. The output is stored in the output
variable, which can be converted to a string and printed.