Skip to content

Instantly share code, notes, and snippets.

@smallnest
Forked from dagoof/piping.go
Created December 27, 2020 05:33
Show Gist options
  • Save smallnest/ace17174d20032dbdd38ec40a8925a5a to your computer and use it in GitHub Desktop.
Save smallnest/ace17174d20032dbdd38ec40a8925a5a to your computer and use it in GitHub Desktop.
piping exec.Cmd in golang (example finds most recently modified file that is not directory or executable)
package main
import (
"os"
"exec"
)
func pipe_commands(commands ...*exec.Cmd) ([]byte, os.Error) {
for i, command := range commands[:len(commands) - 1] {
out, err := command.StdoutPipe()
if err != nil {
return nil, err
}
command.Start()
commands[i + 1].Stdin = out
}
final, err := commands[len(commands) - 1].Output()
if err != nil {
return nil, err
}
return final, nil
}
func main() {
var dirs []string
if len(os.Args) > 1 {
dirs = os.Args[1:]
} else {
dirs = []string{"."}
}
for _, dir := range dirs {
ls := exec.Command("ls", "-Ft", dir)
grep_dir := exec.Command("grep", "-v", "/$")
grep_exe := exec.Command("grep", "-v", "\\*$")
head := exec.Command("head", "-n", "1")
output, err := pipe_commands(ls, grep_dir, grep_exe, head)
if err != nil {
println(err.String())
} else {
print(string(output))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment