Skip to content

Instantly share code, notes, and snippets.

@xvzf
Created February 13, 2023 15:57
Show Gist options
  • Save xvzf/2a5d959cd8c876e1cb102cc4bcf1dfbb to your computer and use it in GitHub Desktop.
Save xvzf/2a5d959cd8c876e1cb102cc4bcf1dfbb to your computer and use it in GitHub Desktop.
Redirect stdin when using exec
package main
import (
"bytes"
"context"
"fmt"
"os/exec"
"sync"
"time"
)
const echoScript = `while read line
do
echo $line
done < /dev/stdin
`
func main() {
var wg sync.WaitGroup
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
var stdin bytes.Buffer
var stdout bytes.Buffer
cmd := exec.CommandContext(ctx, "bash", "-c", echoScript)
cmd.Stdin = &stdin
cmd.Stdout = &stdout
wg.Add(1)
go func() {
defer wg.Done()
cmd.Run()
}()
stdin.WriteString("Hello-World\n")
stdin.WriteString("This is a new line\n")
wg.Wait()
fmt.Println("Stdout:")
fmt.Println(stdout.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment