SoFunction
Updated on 2025-03-05

Golang standard library os/exec executes external commands and gets its output package code example

How to execute external commands and get their output using the os/exec package

Here is a sample code that shows how to execute external commands and get their output using the os/exec package:

package main
import (
	"fmt"
	"os/exec"
)
func main() {
	// Execute external commands	cmd := ("ls", "-l")
	// Capture the output of the command	output, err := ()
	if err != nil {
		("Failed to execute command:", err)
		return
	}
	// Print the output result of the command	(string(output))
}

analyze

In this example, we first import the packages we need to use, including fmt and os/exec.

Then, in the main() function, we use the () function to create a command object representing the external command to be executed. Here we execute the ls -l command.

Next, we execute the command using the Output() method of the command object and capture its output. The Output() method executes the command and returns the standard output result of the command. If an error occurs during the execution of the command, we output the error message and return it.

Finally, we print the output result of the command. Since the () method returns a byte slice, we use the string() function to convert it into a string and print it out.

To run this example, you can use the following command on the command line:

go run 

After running, the ls -l command will be executed and the output result will be printed out.

By using the os/exec package, we can execute external commands in the Go program and get their output results. This is useful for interacting with other system tools, executing scripts, or calling external programs.

The above is the detailed content of the Golang standard library os/exec executing external commands and obtaining its output package code example. For more information about the Golang standard library os exec, please pay attention to my other related articles!