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 <p>This command tells iptables-restore to read its configuration from /etc/iptables.conf. How can we accomplish this with Go's exec.Command()?</p><p><strong>Failed Attempts</strong></p><p>Initial attempts to pass the input file's path as arguments or pipe the file name into stdin were unsuccessful.</p><pre class="brush:php;toolbar:false">// Fails cmd := exec.Command("/sbin/iptables-restore", "<p><strong>Solution: Reading and Writing File Contents</strong></p><p>To successfully execute the command, we must first read the contents of /etc/iptables.conf and then write those contents to the StdinPipe().</p><pre class="brush:php;toolbar:false">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!