Home >Backend Development >Golang >How to Execute External Commands in Go?

How to Execute External Commands in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 02:46:291079browse

How to Execute External Commands in Go?

Executing External Commands in Go

To execute commands external to your Go program, the exec package offers a robust mechanism. This package allows you to initiate a process and halt its execution until completion.

Command Invocation

The Command function initializes an external command execution. To initiate a command named "yourcommand" with the arguments "some" and "args," utilize the following syntax:

cmd := exec.Command("yourcommand", "some", "args")

Blocking Execution

After setting up the command, you can initiate its execution by calling Run(). This method blocks the current thread until the external command finishes running:

if err := cmd.Run(); err != nil { 
    fmt.Println("Error: ", err)
}  

If an error occurs while executing the command, the err variable will contain the details.

Retrieving Output

Alternatively, if you solely require the output from the command, you can employ the Output() function instead of Run(). Output() collects the standard output of the command and stores it in a byte slice:

output, err := cmd.Output()
if err != nil { 
    fmt.Println("Error: ", err)
} 
fmt.Println(string(output)) 

The above is the detailed content of How to Execute External Commands in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn