Last active
October 29, 2023 04:14
-
-
Save mchirico/6045501 to your computer and use it in GitHub Desktop.
Go (golang) program to execute a bash for loop.
This file contains hidden or 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 ( | |
"bytes" | |
"fmt" | |
"log" | |
"os/exec" | |
"strings" | |
) | |
type Result struct { | |
cmd string | |
result interface{} | |
} | |
func bashCmd(s string) []string { | |
cmd := exec.Command("/bin/bash", "-c", s) | |
stdout, err := cmd.StdoutPipe() | |
if err != nil { | |
log.Fatal(err) | |
} | |
stderr, err := cmd.StderrPipe() | |
if err := cmd.Start(); err != nil { | |
log.Fatal(err) | |
} | |
max := 3 | |
lines := make([]string, max) | |
count := 0 | |
bb := bytes.NewBuffer([]byte{}) | |
_, err = bb.ReadFrom(stdout) | |
for { | |
s, err := bb.ReadString('\n') | |
if err != nil { | |
break | |
} | |
lines[count] = s | |
count++ | |
if count+1 >= max { | |
max = max*2 + 10 | |
newLines := make([]string, max) | |
copy(newLines, lines) | |
lines = newLines | |
} | |
// fmt.Printf("%v\n", strings.Fields(s)) | |
} | |
be := bytes.NewBuffer([]byte{}) | |
_, err = be.ReadFrom(stderr) | |
for { | |
s, err := be.ReadString('\n') | |
if err != nil { | |
break | |
} | |
fmt.Printf("%v\n", strings.Fields(s)) | |
} | |
return lines[0:count] | |
} | |
func main() { | |
v := bashCmd("for i in 1 2 3; do echo ${i}; done") | |
fmt.Printf("v=%v len(v)=%v\n", v, len(v)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment