os/exec contexts, stdout/stderr capture, exit status handling, and safe argument passing.
8 min readGo for SREBuild
Basic Execution
os/exec runs external commands. Use exec.Command to create a command, then call Run, Output, or CombinedOutput to execute it.
Gobasic-command-execution.go
25 linesLn 1, Col 1Go
exec.Command creates a command. Run executes and waits. Output captures stdout. CombinedOutput captures both stdout and stderr. Set Dir and Env before running. The command inherits the parent's environment by default.
Context Control
Gocontext-based-command-control.go
60 linesLn 1, Col 1Go
exec.CommandContext creates a context-aware command. When the context is canceled, the command process is killed. For graceful shutdown, start the process, send SIGTERM, wait for exit, then SIGKILL as a fallback.
stdout/stderr Capture
Gocapturing-output.go
47 linesLn 1, Col 1Go
Set cmd.Stdout and cmd.Stderr to capture output. Use io.MultiWriter to capture and display simultaneously. StdoutPipe creates a pipe for streaming. Always call cmd.Wait() after cmd.Start().
Exit Status Handling
Goexit-status-handling.go
34 linesLn 1, Col 1Go
exec.ExitError contains the exit code. Use errors.As to extract it. Common exit codes: 1 (general error), 2 (usage error), 126 (permission denied), 127 (command not found). Handle each code appropriately.
Pipe Patterns
Gocommand-piping.go
35 linesLn 1, Col 1Go
Pipe commands by connecting stdout to stdin. Start commands in order, then wait. For complex pipes, using sh -c is simpler and more readable. The shell handles pipe setup automatically.
Safe Argument Passing
Gosafe-argument-passing.go
33 linesLn 1, Col 1Go
Never concatenate user input into shell commands — this causes shell injection. Always pass arguments as separate strings to exec.Command. Use shellescape.Quote for user input that must be shell-interpolated.
Never use sh -c with user input
exec.Command("sh", "-c", userInput) passes userInput directly to the shell. An attacker can inject arbitrary commands: userInput = "my-pod; rm -rf /". Always use exec.Command with explicit arguments.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.