Created
November 16, 2023 05:12
-
-
Save aatchison/69c262cdf5d77f8dc89702e419398fb7 to your computer and use it in GitHub Desktop.
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 main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"os/exec" | |
) | |
func executeCommand(command string, args ...string) (string, string, error) { | |
cmd := exec.Command(command, args...) | |
var stdoutBuf, stderrBuf bytes.Buffer | |
cmd.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) | |
cmd.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) | |
err := cmd.Run() | |
if err != nil { | |
return "", "", fmt.Errorf("cmd.Run() failed with %s", err) | |
} | |
outStr, errStr := string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()) | |
return outStr, errStr, nil | |
} | |
func main() { | |
out, errOut, err := executeCommand("ls", "-alh") | |
if err != nil { | |
log.Fatalf("Error executing command: %s", err) | |
} | |
fmt.Printf("\nout:\n%s\nerr:\n%s\n", out, errOut) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment