# BashSnippets > Free bash script examples for Linux, DevOps, and sysadmin automation. Copy-paste ready scripts with plain-English explanations. Written by Anguishe — a Linux self-taught user who built this site after learning bash from scratch. ## Author Anguishe — Linux user, bash scripter. Tested every script personally on Ubuntu 22.04 LTS and macOS Ventura. Contact: Anguisheh1@gmail.com ## What This Site Contains # keep in sync with snippets.ts count - 36 ready-to-run bash scripts in /snippets/ — each with step-by-step explanation, variations, common mistakes, and FAQ - 12 interactive tools at /tools/ including script builders, command generators, and debuggers - Bash Boilerplate Generator tool - Beginner FAQ section covering the most common bash questions ## Script Categories - Automation & File Management: backup scripts, file renaming, log cleanup, dated folders, duplicate file detection - Monitoring & Alerts: disk space, CPU/RAM, website uptime, service watchdog - Database: MySQL backup with retention - Process Management: kill by name, service restart - Best Practices: error handling templates (set -euo pipefail), safe script boilerplate - Search & Text: grep patterns, file content search ## All Snippet Pages - [Disk Space Warning Script](https://bashsnippets.xyz/snippets/disk-space-warning) — Copy a disk space warning bash script using df, thresholds, cron, and email alerts. Monitor Linux servers and prevent full drives. - [Automated File Backup](https://bashsnippets.xyz/snippets/automated-file-backup) — Accidental deletion or disk failure permanently destroys data with no undo on Linux. Timestamps each cp -r run with a date string so backups never overwrite each other. - [Delete Old Log Files](https://bashsnippets.xyz/snippets/delete-old-log-files) — Unmanaged log files silently fill /var/log until disk writes fail and services crash. find -mtime deletes .log files older than N days — preview with -print before removing from production. - [Quick System Info Report](https://bashsnippets.xyz/snippets/quick-system-info-report) — Guessing server state during an outage costs response time. One bash script snapshots hostname, uptime, CPU load, RAM, disk usage, and IP address in one run — no extra packages. - [Search Files for Text with grep](https://bashsnippets.xyz/snippets/search-files-for-text-grep) — Opening files manually to find a pattern across a codebase wastes time. grep -rn searches every file recursively and returns every match with filename and line number. - [Check If Website Is Up](https://bashsnippets.xyz/snippets/check-if-website-is-up) — Discovering a site is down from a user complaint means hours of lost traffic already gone. curl -s alerts on any non-200 HTTP status code — cron-schedulable for five-minute checks. - [Bash Error Handling with set -euo pipefail](https://bashsnippets.xyz/snippets/bash-error-handling) — Bash silently continues after failed commands by default — a broken cd followed by rm -rf destroys the wrong directory. set -euo pipefail exits on first failure before damage spreads. - [Bash If/Else Examples](https://bashsnippets.xyz/snippets/bash-if-else-examples) — Comparison operator mistakes in bash scripts cause silent logic failures on unexpected input. Covers if/else, elif, integer and string test operators, file condition checks, and quoting safety. - [Create a Dated Folder](https://bashsnippets.xyz/snippets/create-dated-folder) — Backup directories without timestamps overwrite previous runs and sort unpredictably. date +%Y-%m-%d auto-names folders so ls sorts them chronologically — no packages needed. - [Kill a Process with pkill and pgrep](https://bashsnippets.xyz/snippets/kill-a-process) — The ps/grep/copy-PID/kill workflow takes four steps every time you need to stop a process. pkill by name collapses that to one command — pgrep -l previews matches before terminating. - [File Permissions Security Audit](https://bashsnippets.xyz/snippets/file-permissions-security) — World-writable files on a web server let any compromised script overwrite your application. find -perm 777 audits them and correct chmod 644/755 patterns restore safe permissions. - [Monitor CPU and RAM Usage](https://bashsnippets.xyz/snippets/monitor-cpu-ram-usage) — A runaway process consuming 100% CPU goes undetected until the server becomes unresponsive. top -bn1 and free -m measure CPU and RAM in scripts so cron can alert before impact. - [Send Email Alerts from Bash](https://bashsnippets.xyz/snippets/bash-send-email-alert) — Monitoring scripts without email alerts mean failures go unnoticed until users report them. Wraps mailx or curl SMTP into a reusable alert function with per-run deduplication to prevent inbox flooding. - [MySQL Database Backup Script](https://bashsnippets.xyz/snippets/mysql-database-backup) — A mistaken DROP TABLE or storage failure permanently destroys database data with no built-in undo. mysqldump with gzip compression and 7-day cron rotation keeps nightly backups under 100 MB. - [SSH Key Setup Script](https://bashsnippets.xyz/snippets/ssh-key-setup-script) — Password-based SSH is vulnerable to brute-force attacks and credential leaks on any internet-exposed server. Automates ssh-keygen -t ed25519 and ssh-copy-id to enable key-based auth in one run. - [Find Duplicate Files in Linux](https://bashsnippets.xyz/snippets/find-duplicate-files) — Duplicate files accumulate silently in archives and download folders, wasting gigabytes of disk space. md5sum hashes every file and awk prints only the redundant copies — nothing to install. - [Restart a Service If It Stopped](https://bashsnippets.xyz/snippets/restart-service-if-stopped) — A crashed nginx or postgresql stays down for hours without a watchdog to detect and recover it. systemctl is-active in a cron loop detects stopped services and restarts them within 60 seconds. - [Find Large Files in Linux](https://bashsnippets.xyz/snippets/find-large-files-linux) — Your disk hit 100% and the server stopped. Find the biggest files and directories fast with du and find — excludes virtual filesystems and ranks by size descending. - [Kill Process on Port](https://bashsnippets.xyz/snippets/kill-process-on-port) — EADDRINUSE means something is squatting on your port. Find the process with lsof or ss, then kill it safely — script handles discovery, confirmation, and SIGTERM-to-SIGKILL escalation. - [Rsync Remote Backup](https://bashsnippets.xyz/snippets/rsync-remote-backup) — A local-only backup dies with the machine. Push an incremental, resumable copy to a remote server with rsync over SSH — script with exclude patterns, dry-run, and cron scheduling. - [Check SSL Certificate Expiry with Bash](https://bashsnippets.xyz/snippets/check-ssl-certificate-expiry) — A bash script that connects to any domain over TLS, reads the certificate, and tells you how many days until it expires — before the site goes dark. - [List All Open Ports on Linux](https://bashsnippets.xyz/snippets/list-open-ports-linux) — A bash script that maps every port your server is listening on, along with the process name holding it open — the first step in any security audit. - [Docker Cleanup Bash Script — Reclaim Disk Space from Docker Garbage](https://bashsnippets.xyz/snippets/docker-prune-cleanup) — A bash script that removes stopped containers, unused images, dangling volumes, and build cache from Docker — with a disk-usage report before and after. - [Bash For Loop Examples](https://bashsnippets.xyz/snippets/bash-for-loop-examples) — A for loop over the output of ls word-splits on filenames with spaces and silently skips files. Loop over a glob, a range, an array, or command output the safe way — with the quoting that stops the loop from doing the wrong thing quietly. - [Bash Functions: Return Values, Local Scope, and Reusable Logic](https://bashsnippets.xyz/snippets/bash-functions) — A bash function cannot return a string with return — that keyword sets an exit code only. Use echo plus command substitution or namerefs to return data, and local on every variable to stop silent global collisions. - [Bash Arrays: Indexed, Associative, Append, and Safe Iteration](https://bashsnippets.xyz/snippets/bash-arrays) — Storing a list as a space-separated string breaks the moment one element contains a space, splitting one item into two. Arrays make the space a non-event — covering indexed and associative arrays, append, length, slicing, and safe iteration. - [Bash Argument Parsing: Positional Args, getopts, and Long Flags](https://bashsnippets.xyz/snippets/bash-argument-parsing) — A script that reads $1 as a value will accept --env as that value and deploy nowhere, silently. Parse arguments properly with positional defaults, getopts for short flags, and a while+case loop for GNU-style long flags. - [Bash String Manipulation: Substrings, Replace, and Parameter Expansion](https://bashsnippets.xyz/snippets/bash-string-manipulation) — Field-counting with cut -d/ -f3 returns the wrong slice the moment a URL gains an s for https. Parameter expansion matches on pattern boundaries with no subshell — substrings, prefix/suffix stripping, replace, case conversion, and defaults. - [Read a File Line by Line in Bash](https://bashsnippets.xyz/snippets/bash-read-file-line-by-line) — A while-read loop silently dropped the last server in a monitoring list because the file had no trailing newline — and that was the server that went down. Read a file line by line the correct way: while IFS= read -r line, with the guard that catches the missing final line. - [Bash Functions and Arguments](https://bashsnippets.xyz/snippets/bash-functions-arguments) — A function reused the variable name 'target' without declaring it local, overwrote the caller's variable, and the cleanup step deleted the wrong directory. Write bash functions that take arguments, return values, and don't leak state — with the local keyword that stops a function from clobbering its caller. - [Prevent Overlapping Cron Jobs with flock](https://bashsnippets.xyz/snippets/bash-flock-single-instance) — A cron job that runs long overlaps the next run and stacks copies until the box falls over. Lock it to a single instance with flock — a kernel-held lock that releases on crash, no stale PID files. - [Stop a Hung Command with timeout](https://bashsnippets.xyz/snippets/bash-timeout-command) — A hung cron job is worse than a failed one — it never exits, never frees its lock, and the job silently stops running. Bound any command's runtime with timeout, escalate to SIGKILL, and read the exit code. - [Retry a Command with Exponential Backoff in Bash](https://bashsnippets.xyz/snippets/bash-retry-with-backoff) — A deploy that dies on the first transient error wastes your night re-running it by hand. Retry with exponential backoff and jitter — and learn which failures to retry and which to fail fast on. - [Make API Requests in Bash with curl](https://bashsnippets.xyz/snippets/bash-curl-api-requests) — A curl wrapper for bash that checks HTTP status, times out, and retries transient errors — because plain curl exits 0 on an HTTP 500 and silently poisons everything downstream. - [Parse JSON in Bash with jq](https://bashsnippets.xyz/snippets/bash-parse-json-jq) — How to read fields out of a JSON API response with jq — and why -r, // defaults, and -e are the three things that separate a reliable parse from one that breaks the next time the API reformats. - [Send Slack Alerts from Bash with Incoming Webhooks](https://bashsnippets.xyz/snippets/bash-slack-webhook-alerts) — Post failure alerts to Slack from a bash script with a curl one-liner, a jq-built payload, and a trap on ERR — so a broken backup tells you the night it breaks instead of the day you need it. ## Interactive Tools - [Bash Exit Code Lookup](https://bashsnippets.xyz/tools/bash-exit-code-lookup) — An unhandled exit code hides why a bash script failed and lets errors cascade silently into data loss. Enter any code 0-255 for the plain-English meaning, causes, and a copy-paste error handler. - [Cron Job Builder](https://bashsnippets.xyz/tools/cron-job-builder) — A wrong cron expression runs jobs at the wrong time or skips them entirely with no error output. Build cron expressions visually and verify the human-readable schedule before saving to crontab. - [Chmod Permissions Builder](https://bashsnippets.xyz/tools/chmod-permissions-builder) — Wrong file permissions on a web server expose secrets or let compromised scripts overwrite application files. Build chmod commands visually — shows octal, symbolic notation, and the exact chmod command. - [Bash $PATH Debugger](https://bashsnippets.xyz/tools/path-debugger) — Duplicate and missing PATH entries cause command-not-found errors and slow shell startup by scanning dead directories. Paste your PATH to find duplicates, empty entries, and ordering problems. - [Bash Boilerplate Generator](https://bashsnippets.xyz/tools/bash-boilerplate-generator) — A bash script without error handling silently continues after failures and leaves systems in a broken partial state. Generates a production-ready template with set -euo pipefail, traps, and argument parsing. - [Rsync Command Builder](https://bashsnippets.xyz/tools/rsync-command-builder) — A wrong rsync flag silently overwrites destination files or skips critical data with no error output. Build rsync commands visually — toggle archive, compress, delete, dry-run, SSH, and exclude patterns with a live preview. - [grep Pattern Builder](https://bashsnippets.xyz/tools/grep-pattern-builder) — A wrong grep flag silently matches the wrong files or swallows error output with no warning. Build the exact grep command you need — recursive, case-insensitive, with context lines — and get a plain-English explanation for every output. - [ShellCheck Error Decoder](https://bashsnippets.xyz/tools/shellcheck-error-decoder) — ShellCheck warnings that go unfixed become the exact edge-case bugs that break in production on unexpected input. Enter any SC error code for the rule name, plain-English explanation, and a before/after fix example. - [Bash trap & Signal Handler Builder](https://bashsnippets.xyz/tools/bash-trap-builder) — A script that exits without a trap leaves temp files, lock files, and background jobs behind every time it crashes. Build your trap block visually — pick signals, choose cleanup actions, copy the result. - [Find Command Builder](https://bashsnippets.xyz/tools/find-command-builder) — A find action placed before its filters runs on everything find walks — find -delete before -name empties the whole tree. Build find commands with tests ordered before actions, patterns quoted, and every flag explained. - [Hardened Cron Wrapper Generator](https://bashsnippets.xyz/tools/cron-wrapper-generator) — A bash script that runs long enough to overlap its next run, or hangs on a dead socket, takes down a cron slot silently. Compose flock, timeout, and exponential-backoff retry into a hardened wrapper script with timestamped logging. - [jq Filter Builder](https://bashsnippets.xyz/tools/jq-filter-builder) — Build jq filters by clicking through a real JSON response. Generates the filter and the full curl … | jq command, with a live preview evaluated against your JSON in the browser. ## Pillar Guides - [25 Bash Scripts Every Linux Sysadmin Needs](https://bashsnippets.xyz/guides/bash-scripts-every-sysadmin-needs) — comprehensive guide covering disk monitoring, backups, service management, security, and SSL — 25 production-ready scripts with core commands, cron examples, and full annotated versions - [Bash Scripting for CI/CD Pipelines: GitHub Actions, Deploys, and Docker](https://bashsnippets.xyz/guides/bash-scripting-for-ci-cd-pipelines) — A pipeline reported every step green and deployed broken code, because the build step piped output through tee and bash returned the exit code of tee — always zero. This guide covers the four CI-specific failure modes, safe bash headers, secret validation, PIPESTATUS and pipefail, Docker entrypoints, atomic symlink deploys, and debugging with set -x. - [Bash Text Processing: find, grep, sed, and awk for Logs and Config Files](https://bashsnippets.xyz/guides/bash-text-processing) — The four commands that turn an unreadable log or a tree of config files into an answer — find to locate, grep to search, sed to transform, awk to summarize. The order matters, and the gotchas are the reason most one-liners do the wrong thing quietly. - [Bash Scripts That Survive Cron: Locking, Timeouts, and Retries](https://bashsnippets.xyz/guides/bash-scripts-that-survive-cron) — A script that works when you run it isn't the same as one that survives unattended on cron. The three ways cron jobs die quietly — overlap, hang, transient failure — and the guards that stop each one. - [Shell Scripts That Talk to APIs](https://bashsnippets.xyz/guides/shell-scripts-that-talk-to-apis) — Make curl fail when the API fails, parse the response with jq instead of regex, and alert to Slack when it breaks — the reliable pattern for calling an HTTP API from bash. ## Most important pages - [Bash Exit Code Lookup](https://bashsnippets.xyz/tools/bash-exit-code-lookup): Interactive lookup for bash exit codes 0-255 with plain-English meanings and copy-paste error handlers. - [Cron Job Builder](https://bashsnippets.xyz/tools/cron-job-builder): Visual cron expression builder. Enter a schedule, get a crontab line. - [Chmod Permissions Builder](https://bashsnippets.xyz/tools/chmod-permissions-builder): Build chmod commands visually with a permission matrix showing octal and symbolic output. - [ShellCheck Error Decoder](https://bashsnippets.xyz/tools/shellcheck-error-decoder): Paste a ShellCheck error code, get the plain-English explanation and a before/after fix. - [Bash Boilerplate Generator](https://bashsnippets.xyz/tools/bash-boilerplate-generator): Generate a production-ready bash script template with error handling and argument parsing. - [Rsync Command Builder](https://bashsnippets.xyz/tools/rsync-command-builder): Build rsync commands visually with archive, compress, delete, SSH, and exclude pattern toggles. - [grep Pattern Builder](https://bashsnippets.xyz/tools/grep-pattern-builder): Build grep commands from toggles — recursive, case-insensitive, context lines, file type filters — with a plain-English explanation for every output. - [Find Large Files in Linux](https://bashsnippets.xyz/snippets/find-large-files-linux): Find the biggest files and directories when your disk hits 100% — du + find with exclude patterns. - [Kill Process on Port](https://bashsnippets.xyz/snippets/kill-process-on-port): Free a port blocked by EADDRINUSE — lsof/ss discovery, SIGTERM, then SIGKILL escalation. - [Rsync Remote Backup](https://bashsnippets.xyz/snippets/rsync-remote-backup): Push incremental offsite backups over SSH with rsync — resumable, compressed, cron-scheduled. ## License All scripts: MIT License. Free to use and modify.