Save Command Output to Timestamped Log Files

LINUX REFERENCE

Save Command Output to Timestamped Log Files

Use the Linux date command and tee to create unique, readable log files for repeated troubleshooting commands.

Quick answer

some-command 2>&1 | tee "$(date +%Y%m%d-%H%M%S).log"

This generates a timestamp when the command starts, uses it in the filename, displays output in the terminal and writes the same combined standard output/error stream to the file.

What does 2>&1 mean?

Shell processes normally use file descriptor 1 for standard output and 2 for standard error. 2>&1 redirects stderr to wherever stdout is currently going. That matters with tee: a normal pipe carries stdout, so merging stderr first lets both normal output and errors reach the terminal and the log file.

some-command 2>&1 | tee run.log
Without 2>&1 — stderr can still appear on the terminal but may not be written by tee.
With 2>&1 — both streams are passed through the pipe to tee.

Redirection order matters because the shell processes redirections left-to-right.

Readable timestamp formats

date +%Y%m%d-%H%M%S
# 20260905-143012

date +%Y-%m-%d_%H-%M-%S
# 2026-09-05_14-30-12

Avoid characters such as : when filenames may be moved between operating systems or tools with different filename rules.

Use a variable in a script

#!/usr/bin/env bash

stamp=$(date +%Y%m%d-%H%M%S)
log="diagnostic-${stamp}.log"

some-command 2>&1 | tee "$log"

Quoting the filename variable is a good habit even when the current format contains no spaces.

Append instead of overwrite

some-command 2>&1 | tee -a application.log

Use a timestamped filename when each run should be a separate artifact; use tee -a when multiple runs intentionally belong in one file.

Know what you are capturing

tee receives whatever reaches its standard input. Adding 2>&1 before the pipe merges standard error into standard output so errors are captured too. For long-running or production diagnostics, also consider log rotation, permissions and whether the output may contain secrets.