Home >Backend Development >Golang >How to Properly Pipe Command Outputs in Go's `exec.Command()`?

How to Properly Pipe Command Outputs in Go's `exec.Command()`?

DDD
DDDOriginal
2024-12-15 05:24:101075browse

How to Properly Pipe Command Outputs in Go's `exec.Command()`?

How to Pipe Results in Go's exec.Command() for Command Chains

When using exec.Command() to execute commands in Go, piping the output of one command to another can be challenging.

Consider the following example:

out, err := exec.Command("ps", "cax").Output() // Works and prints command output

However, when attempting to pipe the output of ps to grep, the command fails with an exit status of 1:

out, err := exec.Command("ps", "cax | grep myapp").Output() // Fails

Idiomatic Piping Solution

To resolve the issue, a more idiomatic approach is to use exec.Command() for each command and connect their standard input/output streams directly. Here's how:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    grep := exec.Command("grep", "redis")
    ps := exec.Command("ps", "cax")

    // Connect ps's stdout to grep's stdin.
    pipe, _ := ps.StdoutPipe()
    defer pipe.Close()
    grep.Stdin = pipe

    // Start ps first.
    ps.Start()

    // Run and get the output of grep.
    res, _ := grep.Output()

    fmt.Println(string(res))
}

This allows you to execute multiple commands and pipe their inputs and outputs as needed, providing a flexible way to handle command chains.

The above is the detailed content of How to Properly Pipe Command Outputs in Go's `exec.Command()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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