Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active March 29, 2018 14:52
Show Gist options
  • Save taikedz/7dd08e13bfcda6663addbef4a82fa34e to your computer and use it in GitHub Desktop.
Save taikedz/7dd08e13bfcda6663addbef4a82fa34e to your computer and use it in GitHub Desktop.
Some go learning notes for calling external commands
package main
// Always declare main for the main init part of program
import (
"fmt" // For printing feedback
"os" // For getting args
"os/exec" // For calling external script
"strings" // Std string manipulation lib
)
func numberedlines(myargs []string) {
// The function is called with N parameters, condensed to a list
// The following prints, for each entry, the key `k` (the int index) and the value `v` (the output line)
for k,v := range myargs {
// The key is a special object, whose value appears through concatenation:
// fmt.Println("Got", k, v)
// in formatting strings, use "%v"
// (the odd structures \033[*m are terminal colour codes)
fmt.Printf("\033[32;1m%v\033[0m: %s\n", k, v)
}
}
func firstargofall(myargs...string) {
// Unpacking
// we desmonstrate a function with variable number of arguments
fmt.Println("First unpacked argument was: "+myargs[0])
}
func main() {
// The first token is the program name itself
// drop it
args := os.Args[1:]
// Pass arguments from current program through to command to execute
// the [ARGNAME] + '...' notation unpacks the arguments in place
// so that even if `args` is an array, `Command(...)` itself receives N arguments
cmd := exec.Command("ls", args...)
// Unpack demo
firstargofall(args...)
firstargofall("a", "b", "c")
// out is stdout, err is an actual error object
out, err := cmd.Output()
if ( err != nil ) {
fmt.Println("=== ERROR ===")
fmt.Println(err)
} else {
// string(out) -- the output `out` is a sequence of bytes
outlines := strings.Split(string(out), "\n")
// Another example of unpacking
numberedlines(outlines)
}
}
// Try building and running this item (save as `shelly.go`)
// go build shelly.go && ./shelly -l --color=always
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment