Home > Backend Development > Golang > How to Redirect Input to `exec.Command()` in Go?

How to Redirect Input to `exec.Command()` in Go?

Mary-Kate Olsen
Release: 2024-12-07 15:54:13
Original
266 people have browsed it

How to Redirect Input to `exec.Command()` in Go?

Running Commands with Input Redirection Using exec.Command()

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template