run

package
v0.0.0-...-517f807 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2016 License: MIT Imports: 6 Imported by: 1

README

run

Some simple, useful functions for wrapping exec commands.

Package documentation is here

Documentation

Overview

Packge run contains a few exec command wrappers and a function to get the exit code.

Here is an example usage.

// run a command
// usage: run [-s] command
// examples:
//     $ go run test.go ls -l
//     $ go run test.go -s ls -l
package main

import (
    "fmt"
    "os"
    "github.com/jlinoff/go/run"
)

func main() {
    if len(os.Args) > 1 {
        var cmdargs []string
        var out string
        var err error
        if os.Args[1] == "-s" {
            cmdargs = os.Args[2:]
            out, err = run.CmdSilent(cmdargs)
        } else {
            cmdargs = os.Args[1:0]
            out, err = run.Cmd(cmdargs)
        }
        fmt.Printf("size = %v\n", len(out))
        fmt.Printf("err  = %v\n", err)
      }
    }
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cmd

func Cmd(a []string) (output string, err error)

Cmd runs a command.

The output is displayed and the output is returned.

Example:

// Run the command, display the output.
if _, e := run.Cmd(strings.Fields("ls -l")); e != nil { panic(e) }

func CmdSilent

func CmdSilent(a []string) (output string, err error)

CmdSilent runs a command silently so that the output can be parsed.

The output is displayed and the output is returned.

Example:

// Run the command, do not display the output.
o, e := run.CmdSilent(strings.Fields("ls -l"))
if e != nil { panic(e) }
fmt.Printf("%v", o)

func CmdWithWriters

func CmdWithWriters(a []string, w []io.Writer) (err error)

CmdWithWriters runs a command with customer sinks.

The caller decides what to display and/or receive.

Example:

// Run the command, display the output to stdout, to a file and capture
// it in a buffer.
var buf bytes.Buffer

fp, _ := os.Create("/tmp/log")
defer fp.Close()

w := io.Writer[]{os.Stdout, fp, &buf}
if _, e := run.Cmd(strings.Fields("ls -l")); e != nil { panic(e) }
fmt.Println(buf.String())  // print the buffer

func GetExitCode

func GetExitCode(err error) (code int)

GetExitCode gets the exit code of the last exec call, if possible.

CITATION: http://stackoverflow.com/questions/10385551/get-exit-code-go

Here is how you might use it.

_, e := run.Cmd("ls -l")
if e != nil {
  fmt.Println(e)
  code = GetExitCode(e)
  fmt.Printf("exit code %v", code)
}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL