Bash code snippets with use cases
25 ready-made code building blocks, sorted by topic.
Data structures
- Working with an Array β Store a list of files, hosts or options safely (even with spaces).
- Associative Array β Store mappings such as country code to name or hostname to IP.
- Object Substitute with Functions and a Namespace β Bundle related data and actions, e.g. for configuration or accounts in larger scripts.
Text processing
- Analyze Error Frequency in a Log β Quickly check how many messages per level (INFO/WARN/ERROR) a log file contains.
- Count the Most Frequent Words β Text analysis, e.g. finding the most-used terms in a file.
- Analyze CSV with awk β Sum, filter or reformat table values without Excel.
- Replace Text in Files β Swap configuration values or domains across many files.
- Top IPs from an Access Log β Find suspicious requests (bots, attacks) in a web server log.
Automation
- Backup with a Timestamp β Regularly back up a project folder as a compressed archive (via cron).
- Command with Retries β Try unstable network calls or deployments several times before giving up.
- Parallel Tasks with xargs -P β Process many files (images, logs, archives) simultaneously with several CPU cores.
- Disk Space Warning β Regularly check via cron whether a partition might fill up.
- cron Entries β Start scripts automatically daily, hourly or on weekdays.
Tools
- Options with getopts β Build your own command-line tools with flags like -v and -o file.
- Check Dependencies β At the start of a script, make sure the required programs are installed.
- Confirmation Before Dangerous Actions β Interactive scripts that ask for confirmation before deleting or overwriting.
More snippets
- Hello World β A first test that the terminal and shebang work.
- Variables, Constants and Arithmetic β Store values in scripts, e.g. paths, counters or configuration.
- if / elif / else with [[ ]] β React differently, e.g. check files, distinguish environments or validate input.
- for and while Loops β Process several files or values one after another.
- Function with a Default Value β Define recurring tasks such as logging or checks once.
- Catching Errors: Strict Mode & trap β Scripts that abort cleanly on errors and clean up temp files, e.g. in CI/CD or cron.
- Use Temporary Files Safely β Store intermediate results without leftovers remaining if the script aborts.
- Read a File Line by Line β Process logs, lists or configurations line by line.
- Rename Files in Bulk β Rename photos, exports or reports following a pattern (e.g. .jpeg to .jpg).