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.

Frequently asked questions

How does Bash & Linux handle capture output?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Combine Stdout & Stderr" snippet in Bash & Linux uses `command > file 2>&1`.
Which command does the Bash & Linux example use?
The "Combine Stdout & Stderr" snippet uses `command > file 2>&1`, from the Redirects & Pipes section of the Bash & Linux cheat sheet.
Which stacks cover "capture output" on this page?
Bash & Linux, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Combine Stdout & Stderr": 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.