Capture output

3 snippets across 2 stacks — Bash & Linux, Python

Also written as capture all output

SHBash & Linux

Combine Stdout & Stderr

SH · Redirects & Pipes
syntax
command > file 2>&1
command &> file
command 2>&1 | other
example
make build > build.log 2>&1
./run_tests.sh &> test_results.log
curl https://api.example.com 2>&1 | tee response.log

Note 2>&1 means 'send stderr to wherever stdout is going'. Order matters: > file 2>&1 works (redirect stdout to file, then stderr to stdout's destination). 2>&1 > file does NOT capture stderr to the file. &> is a Bash shorthand for both.

Command Substitution

SH · Shortcuts & Productivity
syntax
$(command)
`command` (legacy)
example
echo "Today is $(date '+%A, %B %d')"
BRANCH=$(git rev-parse --abbrev-ref HEAD)
FILES_CHANGED=$(git diff --name-only | wc -l)
echo "${FILES_CHANGED} files changed on ${BRANCH}"
output
Today is Saturday, April 04
3 files changed on feature/auth

Note Always use $() instead of backticks. $() nests cleanly: $(echo $(whoami)) works; backticks require escaping for nesting. The output has trailing newlines stripped automatically.

PYPython

subprocess Module

PY · Common Standard Library
syntax
import subprocess
subprocess.run([cmd, args], capture_output=True)
example
import subprocess

result = subprocess.run(
    ["echo", "Hello from subprocess"],
    capture_output=True, text=True
)
print(result.stdout.strip())
print(f"Return code: {result.returncode}")
output
Hello from subprocess
Return code: 0

Note Always pass commands as a list, not a string. Use shell=True only when absolutely necessary — it introduces shell injection risks.