Useful Linux Tools and Commands

December 15, 2025

tree - Visualize Directory Structure

The tree command displays directory contents in a tree-like format, making it easy to understand project structures at a glance.

Basic Usage

tree

Filtering with .gitignore

One of the most useful features is respecting .gitignore rules to filter out files that shouldn't be tracked:

tree --gitignore

This flag tells tree to read and respect .gitignore files, filtering out any files/directories that would be ignored by git. Perfect for viewing only the relevant source files in a project.

Note: The --gitignore flag requires tree version 1.8.0 or newer.

Useful Options

# Limit directory depth
tree -L 2

# Combine with gitignore
tree --gitignore -L 2

# Show only directories
tree -d
tree --gitignore -d

# Include hidden files (except gitignored ones)
tree --gitignore -a

# Show file sizes
tree -s

# Show file permissions
tree -p

# Output in color
tree -C

Displaying File and Directory Sizes

The tree command provides powerful options for displaying size information, which is particularly useful for analyzing disk usage.

Show Sizes in Human-Readable Format

# Display file sizes and accumulated directory sizes in human-readable format (KB, MB, GB)
tree -h -s

Explanation:

  • -h: Prints the size of each file in human-readable format (e.g., 1.2K, 3.5M, 2.1G)
  • -s: Shows the size of each file, and for directories, the accumulated size of all contents

Example output:

.
โ”œโ”€โ”€ [4.0K]  src
โ”‚   โ”œโ”€โ”€ [2.5K]  main.py
โ”‚   โ””โ”€โ”€ [1.5K]  utils.py
โ”œโ”€โ”€ [1.2M]  assets
โ”‚   โ”œโ”€โ”€ [500K]  image1.png
โ”‚   โ””โ”€โ”€ [700K]  image2.png
โ””โ”€โ”€ [3.2K]  README.md

Sort by Size

# Sort files and directories by size (largest first)
tree -h -s --sort=size

The --sort=size option sorts entries by their size, making it easy to identify the largest files and directories.

Show Only Directory Sizes

# Display only directories with their accumulated sizes
tree -d -h --du

Explanation:

  • -d: Lists directories only (excludes files)
  • --du: Reports the size of each directory as the accumulation of all files and subdirectories (similar to the du command)

Example output:

.
โ”œโ”€โ”€ [1.2M]  assets
โ”œโ”€โ”€ [4.0K]  src
โ”œโ”€โ”€ [256K]  node_modules
โ””โ”€โ”€ [8.0K]  config

Combine with Other Options

# Show only directories respecting .gitignore, sorted by size
tree -d -h --du --gitignore --sort=size

# Limit depth to 2 levels with sizes
tree -L 2 -h -s

# Show sizes with file permissions
tree -h -s -p

Windows Alternatives

Note: The native Windows Command Prompt tree command does not support displaying file or directory sizes.

Alternatives for Windows:

  1. Third-party GUI tools:

    • TreeSize - Free disk space manager with tree visualization
    • WinDirStat - Graphical disk usage analyzer
  2. PowerShell:

    # Custom PowerShell function to display directory tree with sizes
    Get-ChildItem -Recurse | Select-Object FullName, Length, @{Name="SizeKB";Expression={$_.Length/1KB}}
    
    # Or install the PowerTree module
    Install-Module -Name PowerTree
    Get-PowerTree -Path . -ShowSize

Fallback for Older Versions

If your tree version doesn't support --gitignore, you can use this workaround:

tree -I "$(cat .gitignore | grep -v '^#' | grep -v '^$' | tr '\n' '|' | sed 's/|$//')"

This reads .gitignore, filters out comments and empty lines, and converts patterns to tree's -I (ignore) format.

Installation

# Debian/Ubuntu
sudo apt install tree

# CentOS/RHEL
sudo yum install tree

# macOS
brew install tree

grep - Show Context Lines Around Matches

When searching through log files or source code with grep, seeing the surrounding context of a match can be crucial for understanding what's happening. The grep command provides powerful options to display adjacent lines around your matches.

Key Context Options

These options are widely available in both GNU and BSD versions of grep (which includes Linux and macOS).

OptionDescriptionExample
-A NUMPrint NUM lines of trailing context after each matchgrep -A 2 "pattern" filename
-B NUMPrint NUM lines of leading context before each matchgrep -B 2 "pattern" filename
-C NUMPrint NUM lines of context before and after each matchgrep -C 2 "pattern" filename

Basic Examples

Show Lines After the Match

# Show 3 lines after each match
grep -A 3 "Error" system.log

Example output:

2025-12-15 10:32:15 Error: Database connection timeout
2025-12-15 10:32:16 Retry attempt 1/3
2025-12-15 10:32:17 Connection still failing
2025-12-15 10:32:18 Retry attempt 2/3

This command outputs the line containing "Error" and the three lines immediately following it.

Show Lines Before the Match

# Show 2 lines before each match
grep -B 2 "Warning" system.log

Example output:

2025-12-15 10:30:12 Starting backup process
2025-12-15 10:30:13 Reading configuration
2025-12-15 10:30:14 Warning: Backup directory nearly full

This command outputs the line containing "Warning" and the two lines immediately preceding it.

Show Lines Before and After the Match

# Show 1 line before and 1 line after each match
grep -C 1 "Critical" system.log

# Or, using -A and -B together (equivalent):
grep -B 1 -A 1 "Critical" system.log

Example output:

2025-12-15 10:35:20 Security scan running
2025-12-15 10:35:21 Critical: Unauthorized access attempt detected
2025-12-15 10:35:22 Initiating lockdown protocol

The -C 1 syntax is a convenient shortcut that combines both before and after context.

๐Ÿ““ Note: When using context options, grep typically places a line containing -- between separate groups of matches, unless the matches are close enough for their context lines to overlap.

Enhancing the Output

You can combine context options with other useful grep flags for better readability:

Highlight the Search Term

# Use --color to visually distinguish the exact match
grep -C 3 --color "pattern" filename

The matched text will be highlighted (usually in red), making it easy to spot within the context.

Display Line Numbers

# Add -n to show line numbers for all output lines
grep -C 2 -n "pattern" filename

Example output:

142-2025-12-15 10:30:12 Starting backup process
143-2025-12-15 10:30:13 Reading configuration
144:2025-12-15 10:30:14 Warning: Backup directory nearly full
145-2025-12-15 10:30:15 Available space: 2.3GB
146-2025-12-15 10:30:16 Proceeding with backup

Note how the matching line (144) has a : while context lines have -.

Combine All Enhancements

# Full example with line numbers, color, and 3 lines of context
grep -C 3 --color -n "pattern" filename

This is the most informative combination for debugging and analysis.

Real-World Use Cases

Debugging Application Errors

# Find exceptions with surrounding stack trace
grep -A 10 "Exception" app.log

# Find errors with preceding context to see what triggered them
grep -B 5 "ERROR" app.log

Analyzing Configuration Files

# Find a setting and see related configuration
grep -C 3 "port" /etc/nginx/nginx.conf

Searching Source Code

# Find function calls with surrounding code
grep -C 5 "authenticate" src/**/*.py

# Find TODO comments with context
grep -B 2 -A 5 "TODO" src/**/*.js

Log Analysis

# Find warning patterns with context, highlight matches, show line numbers
grep -C 2 --color -n "timeout\|failed\|error" system.log

# Search multiple files and show which file each match came from
grep -C 3 -n "Exception" *.log

Advanced Tips

Case-Insensitive Search with Context

# Combine -i (ignore case) with context options
grep -i -C 2 "warning" system.log

Recursive Search with Context

# Search all files in directory tree with context
grep -r -C 3 "TODO" ./src/

Invert Match with Context

# Show lines NOT matching pattern, with context
grep -v -C 2 "debug" app.log

Regular Expressions with Context

# Use regex patterns with context
grep -E -C 3 "error|warning|critical" system.log

Summary

For quick reference, here's the most commonly used command:

grep -C 3 --color -n "search_term" filename

This gives you:

  • 3 lines of context before and after each match
  • Colored highlighting of the match
  • Line numbers for easy navigation

These context options transform grep from a simple search tool into a powerful debugging and analysis instrument, essential for any developer or system administrator working with log files and codebases.

Bash Output Redirection - Capturing stdout and stderr

The Problem

When trying to capture Docker logs to a file:

docker logs -f container_id > output.txt

You might notice some output still appears in the terminal: > redirects stdout only. With a non-TTY container, Docker can preserve the application's stdout and stderr as separate streams; the CLI can also report its own errors on stderr. This is not specific to follow mode. Containers using a TTY may already have combined their streams.

The Solution

Use &> to capture both stdout and stderr:

docker logs -f container_id &> output.txt

Now all output goes to the file.

For a POSIX-compatible spelling, use > output.txt 2>&1. Docker-specific log paths, cleanup and rotation are covered in Docker ๅฎนๅ™จๆ—ฅๅฟ—็ฎก็†๏ผšๆŸฅ็œ‹ใ€ๅฏผๅ‡บใ€ๆธ…็†ไธŽ่ฝฎ่ฝฌ.

Redirection Syntax Reference

SyntaxWhat it captures
> filestdout only
2> filestderr only
&> filestdout + stderr (Bash shorthand)
> file 2>&1stdout + stderr (POSIX compatible)

Understanding the Syntax

  • 1 = stdout (standard output) โ€” normal program output
  • 2 = stderr (standard error) โ€” error messages, warnings, debug info
  • & in &> means "both file descriptors"
  • 2>&1 means "redirect stderr (2) to wherever stdout (1) is going"

More Examples

# Save only errors to a file, show normal output in terminal
docker logs container_id 2> errors.txt

# Save stdout and stderr to separate files
docker logs container_id > output.txt 2> errors.txt

# Discard stderr completely
docker logs container_id 2>/dev/null

# Append instead of overwrite
docker logs container_id &>> output.txt

Common Use Cases

# Capture build output including errors
npm run build &> build.log

# Save test results with any error output
pytest &> test_results.txt

# Capture curl response including connection errors
curl https://api.example.com &> response.txt

Redirection Order Matters

The shell applies redirections from left to right. 2>&1 duplicates stdout's destination at that moment; it does not track later changes to stdout. Bash redirections

# Both streams go to output.txt
some_command > output.txt 2>&1

# stderr keeps the original stdout destination (usually the terminal)
some_command 2>&1 > output.txt

> truncates an existing destination file before the command runs; >> appends. To append both streams, use some_command >> output.txt 2>&1. Bash also supports &>> output.txt.

tee Copies a Stream; echo Does Not

The attempted pipeline in the Docker discussion was equivalent to:

(docker logs -f 8bce > gongkard_log.txt | echo) > 1.txt

The explicit redirection sends Docker's stdout to gongkard_log.txt, overriding its pipe destination. echo does not copy standard input; with no arguments, it prints a newline. The outer redirection therefore does not collect the Docker log stream. Adding parentheses changes grouping, not how echo works.

Use tee to copy input into files and onward to stdout. It overwrites the named files by default; -a appends. GNU tee

# Save to a file and display in the terminal
docker logs --tail 100 -f 8bce 2>&1 | tee gongkard_log.txt

# Save to two files without displaying the log stream
docker logs --tail 100 -f 8bce 2>&1 | tee gongkard_log.txt > 1.txt

# Append to both files and also display in the terminal
docker logs --tail 100 -f 8bce 2>&1 | tee -a gongkard_log.txt 1.txt

These exported files have their own lifetime. Docker log rotation does not limit them.

Follow Mode Does Not Immediately Return an Exit Status

docker logs -f keeps streaming new output. In docker logs -f ... && echo Success, the second command waits until the first exits successfully; it is not a startup notification. For a completed export, use a bounded query without -f. Docker logs reference

if docker logs --since 30m 8bce > gongkard_log.txt 2>&1; then
  printf 'Export completed\n'
else
  printf 'Export failed; inspect the output file\n' >&2
fi

When checking a pipeline's status in Bash, set -o pipefail makes an upstream failure visible even if tee succeeds. It still does not make a running follow command finish, and a successful export does not prove that the application itself is healthy. Bash pipelines

References

  1. Free Software Foundation. (n.d.). Redirections. GNU Bash Reference Manual.
  2. Free Software Foundation. (n.d.). tee: Redirect output to multiple files or processes. GNU Coreutils Manual.
  3. Docker. (n.d.). docker container logs. Docker Docs. Retrieved November 13, 2026.
  4. Free Software Foundation. (n.d.). Pipelines. GNU Bash Reference Manual.

ยฉ 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-15). Useful Linux Tools and Commands. https://caiborui.com/blog/2025-12-15-en-useful-linux-tools

@misc{borui2025-7e954138,
  author = {borui},
  title = {{Useful Linux Tools and Commands}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-15-en-useful-linux-tools}
}