In Golang, you can execute an external command or program using the syscall
package. Here's an example of how you can do it:
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
)
func main() {
// Command to execute
cmd := exec.Command("ls", "-l")
// Set command's stdout and stderr to current process's stdout and stderr
// so that command's output will be printed to the console
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Run the command
err := cmd.Run()
if err != nil {
// Handle error if any
if exitError, ok := err.(*exec.ExitError); ok {
// The command failed, exit status will be in exitError.ExitCode()
fmt.Println("Command failed with exit status:", exitError.ExitCode())
} else {
// Some other error occurred
fmt.Println("Command execution failed:", err)
}
}
// Get the command's exit status
if exitError, ok := err.(*exec.ExitError); ok {
// Exit status will be in exitError.Sys().(syscall.WaitStatus)
if status, ok := exitError.Sys().(syscall.WaitStatus); ok {
fmt.Println("Exit status:", status.ExitStatus())
}
}
}
In this example, we use the exec.Command
function to create a command object for the external command we want to execute. We set the command's Stdout
and Stderr
to the current process's Stdout
and Stderr
so that the command's output will be printed to the console. Then, we call the command's Run
method to start the execution of the command.
If the command fails, the error returned by Run
will be of type exec.ExitError
, and you can get the exit status using exitError.ExitCode()
. If the command succeeds, Run
will return nil
. You can also get the exit status using exitError.Sys().(syscall.WaitStatus)
, and then access the exit status using status.ExitStatus()
.
Note: The specific external command executed in this example is ls -l
, which lists files and directories in the current directory on Unix-based systems. You can replace it with any other command you want to execute.