Bash Examples

Browse Bash examples

bashSnippet

Bash Array Bulk Operations

Manipulate indexed arrays safely with quoted expansion, slice and search builtins, and mapfile ingestion so filenames with spaces survive round trips.

bashSnippet

Parse Options With getopts

Parse short options and their arguments with getopts so a shell script exposes a predictable CLI instead of positional guesswork.

bashSnippet

Retry a Command With Backoff

Retry a shell command that may fail transiently, waiting longer between attempts and reporting the last error when all tries are exhausted.

bashSnippet

Arithmetic Operations and Math

Performs arithmetic operations using $(( )), let, and expr including integer math, bitwise operations, increment/decrement, and conditional expressions.

bashSnippet

Conditional Tests and Logic

Demonstrates if/elif/else conditionals with test commands, file tests, string tests, numeric comparisons, and logical operators in Bash scripts.

bashSnippet

Functions and Return Values

Defines and uses Bash functions with local variables, return values, argument passing, and recursive calls for modular and reusable script logic.

bashSnippet

Getopts for Option Parsing

Uses getopts to parse command-line options with short flags, default values, and argument validation for building robust CLI tools in Bash.

bashSnippet

Loops and Iteration Patterns

Demonstrates for loops, while loops, until loops, and C-style loops with break, continue, and range iteration for various data processing patterns.

bashSnippet

Advanced Parameter Expansion

Demonstrates advanced Bash parameter expansion patterns including defaults, alternatives, substring, case modification, and variable indirection.

bashSnippet

Pipelines and Data Flow

Constructs multi-stage pipelines connecting commands with pipes for data transformation, filtering, and aggregation in a streaming fashion.

bashSnippet

Input/Output Redirection

Demonstrates stdin, stdout, stderr redirection including appending, merging streams, discarding output, and using file descriptors for advanced I/O control.

bashSnippet

String Manipulation Operations

Demonstrates Bash string manipulation including substring extraction, pattern replacement, case conversion, trimming, and splitting operations.

bashSnippet

Traps for Signal Handling

Sets up trap handlers for signals like EXIT, INT, TERM, and ERR to ensure cleanup, graceful shutdown, and error recovery in Bash scripts.

bashSnippet

Xargs for Parallel Execution

Uses xargs to build and execute commands from standard input with parallel execution, argument batching, and null-delimiter handling for safe processing.