Created
December 14, 2011 16:51
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} | |
} |
There is a problem, defunct process will be left before main process quit.
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
Few changes for go 1:
< "os/exec"
Thanks for the example