Skip to content

Instantly share code, notes, and snippets.

@lorello
Last active May 11, 2023 16:59
Show Gist options
  • Select an option

  • Save lorello/06b5a28069e00ab847d2872afc90ed04 to your computer and use it in GitHub Desktop.

Select an option

Save lorello/06b5a28069e00ab847d2872afc90ed04 to your computer and use it in GitHub Desktop.
Exec a command in golang and pass an input to a command using stdin
package main
import (
"log"
"os/exec"
"strings"
)
func main() {
// passo un comando e una stringa di input per esso
// voglio passare da stdin per evitare di dover fare escaping
// in bash
shellout, err := Shellout("./test-input.sh", "{ \"id\"=\"123\" }")
if err != nil {
log.Println("Error:", err.Error())
}
log.Println("output: ", shellout)
}
func Shellout(command string, commandInput string) (string, error) {
cmd := exec.Command(command)
log.Printf("shellout %q %q", command, commandInput)
cmd.Stdin = strings.NewReader(commandInput)
output, err := cmd.Output()
if err != nil {
return "", err
}
str := string(output)
return str, err
}
#!/bin/bash
#
# $ echo "Ciao" | ./test-input.sh
# test: Ciao
#
read
echo "$REPLY"
while read line
do
echo "$line"
done < "/dev/stdin"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment