Skip to content

gopowersupply/shell

Repository files navigation

GitHub Go version Build Status Go Report Card Coverage Status code-coverage GoDoc GitHub tag (latest SemVer) GitHub last commit GitHub issues

The package to allow interaction with your system shell.

It should support Windows, macOS and all Linux-based distros. Actually, was tested on Ubuntu only. I am open to your suggestions.

Get it from github:

go get -u https://github.com/gopowersupply/shell

Documentation can be found here

Examples

This is a simplest way to execute a command from default shell:

    res, err := shell.Cmd("echo hi")
    panic(err)
    // res: hi    

⚠️ Be aware that command result string truncates. This means that if the real output is ' sample output\n' you will get 'sample output'

You can make a command to use it later with additional params:

    echo := shell.NewCommand("echo")
    // [...]
    res, _ := echo.Exec("text")
    // res: text

You can use a custom shell to execution:

    res, _ := shell.New("/bin/sh", []string{"-c"}).Cmd("echo test")
    // res: test

Alternative to create a new command from custom shell:

    sh := shell.New("/bin/sh", []string{"-c"})
    echo := sh.NewCommand("echo")
    res, _ := echo.Exec("hey", "there")
    // res: hey there

Errors handling

This package has an own error type CommandError
You can pass the package errors through your functions then detect it via errors.As:

    func ExecUnexpected() error {
    	// [...] Here your other returns with own errors
        _, err := shell.Cmd("unexpected_command")
        if err != nil {
        	return err
        }
        // [...] Here your other returns with own errors
    }

    func main() {
    	err := ExecUnexpected()    	
    	if shell.IsCommandError(err) {
    		// [...] to do anything
    	} else {
    		// [...] to do something other    		
    	}
    }

And you can use errors.As(err, &shell.CommandError{}) as alternative.