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

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

Barbara Streisand
Release: 2024-12-05 04:21:09
Original
418 people have browsed it

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

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

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

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