The snippet library.
Small, practical examples. Search by task or narrow things down below.
Substitute values into a multiline template
Bash Scripts: An unquoted heredoc delimiter enables parameter expansion in the template.
Bash Scripts✓ Tested
Sum a range of integers
Use an arithmetic loop without launching external processes.
arithmetic✓ Tested
Test a function’s success status
Bash Scripts: Test a function’s success status with a small standalone Bash program.
Bash Scripts✓ Tested
Test numeric divisibility with a remainder
Bash Scripts: The modulo operator computes an integer remainder.
Bash Scripts✓ Tested
Use a counted Bash loop
Bash Scripts: Use a counted Bash loop with a small standalone Bash program.
Bash Scripts✓ Tested
Use a default value for an unset variable
Supply a fallback without changing the original variable.
parameter expansion✓ Tested
Use a fallback for an unset variable
Bash Scripts: Use a fallback for an unset variable with a small standalone Bash program.
Bash Scripts✓ Tested
Use a function’s exit status as a boolean result
Bash Scripts: Return zero for success and test the function directly in a conditional.
Bash Scripts✓ Tested
Use a recursive function for a bounded calculation
Bash Scripts: A recursive factorial demonstrates local variables and a clear base case.
Bash Scripts✓ Tested
Use an alternate value only when a variable is nonempty
Bash Scripts: The colon-plus expansion returns its word only when the parameter has a nonempty value.
Bash Scripts✓ Tested
Validate the number of positional arguments
Bash Scripts: Use the argument count to enforce a simple command-line contract.
Bash Scripts✓ Tested
Visit associative-array keys in a stable order
Bash Scripts: Associative arrays have no defined iteration order, so sort their keys explicitly.
Bash Scripts✓ Tested