Skip to content

Instantly share code, notes, and snippets.

@inkel
Created February 20, 2026 12:38
Show Gist options
  • Select an option

  • Save inkel/92487e03f258b56fe1d0344a778d637b to your computer and use it in GitHub Desktop.

Select an option

Save inkel/92487e03f258b56fe1d0344a778d637b to your computer and use it in GitHub Desktop.
Simple Go function to pipe an `exec.Cmd` to `jq`
package pipe
func shell2jq(ctx context.Context, jqScript string, command string, args ...string) (string, error) {
// Here be dragons
var (
cmd = exec.CommandContext(ctx, command, args...)
jq = exec.CommandContext(ctx, "jq", "-r", jqScript)
r, w = io.Pipe()
g = new(errgroup.Group)
out bytes.Buffer
)
// pipe the commands
jq.Stdin, cmd.Stdout = r, w
cmd.Stderr = os.Stderr
jq.Stderr = os.Stderr
jq.Stdout = &out
g.Go(func() error {
defer w.Close()
if err := cmd.Run(); err != nil {
return fmt.Errorf("running %s: %w", cmd, err)
}
return nil
})
g.Go(func() error {
defer r.Close()
if err := jq.Run(); err != nil {
return fmt.Errorf("running %s: %w", jq, err)
}
return nil
})
if err := g.Wait(); err != nil {
return "", err
}
return strings.TrimSpace(out.String()), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment