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
Release: 2024-12-15 05:24:10
Original
987 people have browsed it

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template