Skip to content

nhatthm/go-exec

Repository files navigation

Exec

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

Package exec runs external commands.

Prerequisites

  • Go >= 1.22

Install

go get go.nhat.io/exec

Usage

Run a command:

package example_test

import (
	"bytes"
	"fmt"

	"go.nhat.io/exec"
)

func ExampleRun() {
	outBuf := new(bytes.Buffer)
	errBuf := new(bytes.Buffer)

	_, err := exec.Run("echo", exec.WithArgs("hello world"),
		exec.WithStdout(outBuf),
		exec.WithStderr(errBuf),
	)

	if err != nil {
		panic(err)
	}

	fmt.Println(outBuf.String())
	fmt.Println(errBuf.String())

	// Output:
	// hello world
	//
}

Run a command with pipes:

package example_test

import (
    "bytes"
    "fmt"

    "go.nhat.io/exec"
)

func ExampleRun_pipe() {
	outBuf := new(bytes.Buffer)
	errBuf := new(bytes.Buffer)

	_, err := exec.Run("echo", exec.WithArgs("hello world"),
		exec.WithStdout(outBuf),
		exec.WithStderr(errBuf),
		exec.Pipe("grep", "-o", "hello"),
		exec.Pipe("tr", "[:lower:]", "[:upper:]"),
	)

	if err != nil {
		panic(err)
	}

	fmt.Println(outBuf.String())
	fmt.Println(errBuf.String())

	// Output:
	// HELLO
	//
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this