package sh import ( "log" "os" "strings" "github.com/codeskyblue/go-sh" ) // Shell contains the created Session and Run convenience methods type Shell struct { *sh.Session } // New creates a Shell with all environment variables copied to it. func New() *Shell { session := sh.NewSession() env := os.Environ() for _, variable := range env { tokens := strings.Split(variable, "=") session.SetEnv(tokens[0], tokens[1]) } return &Shell{Session: session} } // NewInDir creates a new shell in the provided directory. func NewInDir(dir string) *Shell { shell := New() shell.SetDir(dir) return shell } // Run shell command without breaking command up into variadic arguments, // returns output and err func (sh Shell) Run(command string) (string, error) { tokens := strings.Split(command, " ") out, err := sh.Command(tokens[0], tokens[1:]).Output() if err != nil { return string(out), err } return string(out), nil } // RunE runs the shell command but discards the string output, to enable inlining // for situations where only the error matters. func (sh Shell) RunE(command string) error { _, err := sh.Run(command) return err } // Run shell command without breaking command up into variadic arguments, // returns combine outputs and err func (sh Shell) RunCombineOutput(command string) (string, error) { tokens := strings.Split(command, " ") out, err := sh.Command(tokens[0], tokens[1:]).CombinedOutput() if err != nil { return string(out), err } return string(out), nil } // RunOrDie command that will fatally error if the command does not succeed func (sh Shell) RunOrDie(command string) string { out, err := sh.Run(command) if err != nil { log.Fatal(err) } return out }