Home >Backend Development >Golang >How to Redirect Input to `exec.Command()` in Go?
In Go, exec.Command() offers a convenient way to execute external commands. However, handling input redirection can be challenging. This discussion explores how to use exec.Command() to run the command /sbin/iptables-restore < /etc/iptables.conf.
Initially, attempts to set up the command with < and < /etc/iptables.conf failed. Piping the file name through stdin also didn't work. Instead, to redirect input to stdin, it's necessary to first read the contents of the input file, /etc/iptables.conf.
Here's how to accomplish this:
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) } }
This approach allows us to read the file's content, pipe it to the command's stdin, and then start the command with the desired input redirection.
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!