make build > build.log2>&1./run_tests.sh&> test_results.logcurl https://api.example.com2>&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.
echo"Today is $(date '+%A, %B %d')"BRANCH=$(git rev-parse --abbrev-ref HEAD)FILES_CHANGED=$(gitdiff--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.
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.