Wrote a simple program that calls “ls”, then passes each line through regexp filtering for files that end in an “s”. ls is used only for the purposes of learning the exec package. How can I improve the code below to be more correct/succinct/go-ish?
package main
import (
"bufio"
"fmt"
"os/exec"
"regexp"
)
func main() {
cmd := exec.Command("ls")
stdout, _ := cmd.StdoutPipe()
s := bufio.NewReader(stdout)
cmd.Start()
go cmd.Wait()
for {
l, _, err := s.ReadLine()
if err != nil {
break
}
if m, err := regexp.Match(".*s$", l); m && err == nil {
fmt.Println(string(l))
}
}
}
The Cmd.Output example in the standard documentation is pretty succinct. It doesn’t do any text processing, but it shows how to execute a command and get the output with a single function call.
Here’s a way to combine that example with yours,
If the goal is to get a broad overview of the package, experiment with a number of the functions and methods to learn their different capabilities. Experiment with command arguments. Experiment with the different fields of the Cmd struct. Try not to get too distracted with other packages like regexp, just look for the simplest examples that exercise a package feature.
Of course if you see how you might use an exec feature in a real application, try it. You’ll learn that one feature in more depth.