Home >Backend Development >Golang >How to Redirect Input to exec.Command() in Go?
Redirecting Input with exec.Command()
Issuing commands with input redirection in Go can be a challenge. Consider the common command-line operation:
/sbin/iptables-restore < /etc/iptables.conf
This command tells iptables-restore to read its configuration from /etc/iptables.conf. How can we accomplish this with Go's exec.Command()?
Failed Attempts
Initial attempts to pass the input file's path as arguments or pipe the file name into stdin were unsuccessful.
// Fails cmd := exec.Command("/sbin/iptables-restore", "<", "/etc/iptables.conf") // Also fails cmd := exec.Command("/sbin/iptables-restore", "< /etc/iptables.conf") // Attempt to pipe file name into stdin // Fails cmd := exec.Command("/sbin/iptables-restore") stdin, err := cmd.StdinPipe() if err != nil { log.Fatal(err) } err = cmd.Start() if err != nil { log.Fatal(err) } io.WriteString(stdin, "/etc/iptables.conf")
Solution: Reading and Writing File Contents
To successfully execute the command, we must first read the contents of /etc/iptables.conf and then write those contents to the StdinPipe().
package main import ( "io" "io/ioutil" "log" "os/exec" ) func main() { bytes, err := ioutil.ReadFile("/etc/iptables.conf") if err != nil { log.Fatal(err) } cmd := exec.Command("/sbin/iptables-restore") stdin, err := cmd.StdinPipe() if err != nil { log.Fatal(err) } err = cmd.Start() if err != nil { log.Fatal(err) } _, err = io.WriteString(stdin, string(bytes)) if err != nil { log.Fatal(err) } }
The above is the detailed content of How to Redirect Input to exec.Command() in Go?. For more information, please follow other related articles on the PHP Chinese website!