Created
February 20, 2026 12:38
-
-
Save inkel/92487e03f258b56fe1d0344a778d637b to your computer and use it in GitHub Desktop.
Simple Go function to pipe an `exec.Cmd` to `jq`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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