Documentation
¶
Overview ¶
Package shell provides utilities for building command strings to execute in sh. It also provides a wrapper around os/exec, but instead of an Args slice you can pass in a format string.
A common use case is generating safe strings for passing to commands that execute other shell commands (such as SSH). Otherwise you may find this a more convenient way to build up commands vs passing a slice to exec.Command
This way of interacting with the shell is inspired by the csprintf related functions from libphutil
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Commandf ¶
Commandf runs a shell command based on the format string
Example ¶
package main import ( "fmt" "log" "github.com/keegancsmith/shell" ) func main() { out, err := shell.Commandf("echo %s", "hello world").Output() if err != nil { log.Fatal(err) } fmt.Print(string(out)) }
Output: hello world
Example (Redirect) ¶
package main import ( "bytes" "fmt" "log" "strings" "github.com/keegancsmith/shell" ) func main() { var stdout, stderr bytes.Buffer cmd := shell.Commandf("echo %s; echo %s 1>&2", "hello from stdout", "hello from stderr") cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { log.Fatal(err) } fmt.Println("stdout:", strings.TrimSpace(stdout.String())) fmt.Println("stderr:", strings.TrimSpace(stderr.String())) }
Output: stdout: hello from stdout stderr: hello from stderr
func EscapeArg ¶
EscapeArg escapes a string such that it is safe to pass to a shell. It is a re-implementation of PHP's escapeshellarg
func ReadableEscapeArg ¶
ReadableEscapeArg will not escape strings that do not requiring escaping. Note that it is conservative, so may escape strings which do not require it.
func Sprintf ¶
Sprintf generates a shell command with the format arguments escaped.
Example ¶
package main import ( "fmt" "github.com/keegancsmith/shell" ) func main() { // Generates shell command to find number of go files on a remote machine host := "foo.com" findCmd := shell.Sprintf("find . -iname %s | wc -l", "*.go") remoteCmd := shell.Sprintf("ssh ubuntu@%s %s", host, findCmd) fmt.Println(remoteCmd) }
Output: ssh ubuntu@foo.com 'find . -iname '\''*.go'\'' | wc -l'
Types ¶
This section is empty.