Go by Example: Exec’ing Processes

The Go os/exec package provides a way to execute shell commands and retrieve the results. Here’s a simple example of executing a shell command and printing the output:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	// exec.Command creates a Cmd structure to represent this command.
	cmd := exec.Command("ls", "-l", "-a", "-h")

	// Run the command and retrieve the standard output.
	out, err := cmd.Output()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Print the output.
	fmt.Println(string(out))
}

This will execute the ls command with the arguments -l, -a, -h and print the resulting output.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *