Skip to content

Instantly share code, notes, and snippets.

@dagoof
Created December 14, 2011 16:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dagoof/1477401 to your computer and use it in GitHub Desktop.
Save dagoof/1477401 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))
}
}
}
@mkinney
Copy link

mkinney commented Aug 26, 2012

Few changes for go 1:
< "os/exec"

"exec"
< func pipe_commands(commands ..._exec.Cmd) ([]byte, error) {
func pipe_commands(commands ..._exec.Cmd) ([]byte, os.Error) {
< println(err)
println(err.String())

Thanks for the example

@gpfeng
Copy link

gpfeng commented Apr 24, 2015

There is a problem, defunct process will be left before main process quit.

@baiyutang
Copy link

baiyutang commented Mar 20, 2023

There is a problem, defunct process will be left before main process quit.

!!NOTICE, please use this code >> https://gist.github.com/kylelemons/1525278

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment