Skip to content

Instantly share code, notes, and snippets.

@eSlider
Created February 27, 2020 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eSlider/b8cd54ab25600ce9e8098b7fe55a9e29 to your computer and use it in GitHub Desktop.
Save eSlider/b8cd54ab25600ce9e8098b7fe55a9e29 to your computer and use it in GitHub Desktop.
Golang Shell Script
//usr/bin/env test -x $0 && (go build -o "${0}c" "$0" && "${0}c" $@; r=$?; rm -f "${0}c"; exit "$r"); exit "$?"
//
// The top "comment" defines shebang
// More over:
// * https://gist.github.com/posener/73ffd326d88483df6b1cb66e8ed1e0bd
// * https://getstream.io/blog/switched-python-go/
package main
import (
"bytes"
"fmt"
"log"
"os"
"os/exec"
)
func main() {
// List directory
var cmd = Exec([]string{"ls", "-l"}...)
// Print stdout
fmt.Printf("out:\n%s\n", string(cmd.Stdout.(*bytes.Buffer).Bytes()))
// Print stderr
fmt.Printf("err:\n%s\n", string(cmd.Stderr.(*bytes.Buffer).Bytes()))
// Return code.
os.Exit(0)
}
func Exec(arg ...string) *exec.Cmd {
var stdout, stderr bytes.Buffer
cmd := exec.Command(arg[0], arg[1:]...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
log.Fatalf("cmd.Run() failed with %s\n", err)
}
return cmd
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment