Last active
May 11, 2023 16:59
-
-
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
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 ( | |
| "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 | |
| } |
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
| #!/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