Skip to content

Instantly share code, notes, and snippets.

@adnaan
Last active September 25, 2019 13:02
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save adnaan/6ca68c7985c6f851def3 to your computer and use it in GitHub Desktop.
Save adnaan/6ca68c7985c6f851def3 to your computer and use it in GitHub Desktop.
Parse and execute a simple bash script.
ls -la
echo "hello"
tree
adb devices
adb wait-for-device #example of a long running task
package main
import (
"bufio"
"fmt"
shlex "github.com/flynn/go-shlex"
"gopkg.in/pipe.v2"
"os"
"time"
)
func readLines(path string) []string {
inFile, _ := os.Open(path)
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines
}
func execScript(script []string, status chan string, log chan string, quit chan bool) {
s := pipe.NewState(nil, nil)
go func() {
for _, v := range script {
args, err := shlex.Split(v)
if err != nil {
fmt.Println(err)
}
p := pipe.Line(pipe.Exec(args[0], args[1:]...), pipe.Filter(func(line []byte) bool {
log <- string(line)
return true
}))
p(s)
cmdline := args[0] + " " + fmt.Sprintf("%s", args[1:])
s.RunTasks()
status <- cmdline
}
}()
<-quit
s.Kill()
}
func main() {
script := readLines("script.sh")
status := make(chan string)
log := make(chan string)
quit := make(chan bool)
go execScript(script, status, log, quit)
loop:
for {
select {
case s := <-status:
fmt.Printf(">>task done: %v\n", s)
case l := <-log:
fmt.Println(l)
case <-time.After(time.Second * 10):
fmt.Println("timed out\n")
quit <- true
break loop
}
}
}
@toravir
Copy link

toravir commented Jul 9, 2018

did u consider using go parser to build an AST - so that u can handle loops, assignments etc ??

@rbucker
Copy link

rbucker commented Sep 25, 2019

this would be a great idea if I could extract all the multiline EXPORTS and execute ${var} substitutions

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