Skip to content
$bash-snippets

Bash Script Library

45 copy-paste bash scripts with plain-English explanations. ShellCheck-clean.

45scripts
12free tools
0logins required

Beginner Scripts (15)

beginner · monitor · cron-ready · df

Disk Space Warning Script

Copy a disk space warning bash script using df, thresholds, cron, and email alerts. Monitor Linux se...

Full guide →
beginner · backup · cron-ready · rsync

Automated File Backup

A deleted file on Linux has no undo. This bash backup script timestamps every cp -r run with a date...

Full guide →
beginner · monitor · reporting · system

Quick System Info Report

Guessing server state mid-outage costs time. One bash script reports hostname, uptime, CPU load, RAM...

Full guide →
beginner · grep · search · text

Search Files for Text with grep

Opening files one by one to find a string wastes time. grep -rn searches every file under a director...

Full guide →
beginner · monitor · curl · uptime

Check If Website Is Up

Learning a site is down from a user complaint means the outage already cost you. A bash curl check t...

Full guide →
beginner · conditionals · basics · if

Bash If/Else Examples

The wrong comparison operator makes a bash if statement fail silently on unexpected input. if/else,...

Full guide →
beginner · files · date · mkdir

Create a Dated Folder

Backup folders without dates overwrite old runs and sort unpredictably. date +%Y-%m-%d names each fo...

Full guide →
beginner · disk · du · find · cleanup · troubleshooting

Find Large Files in Linux

Disk at 100% and the server stopped. Find the biggest files and directories fast with du and find, s...

Full guide →
beginner · ports · lsof · ss · kill · networking · troubleshooting

Kill Process on Port

EADDRINUSE means something already holds your port. Find the process with lsof or ss and kill it saf...

Full guide →
beginner · ports · networking · ss · netstat · security · audit · lsof

List All Open Ports on Linux

A bash script that maps every port your server is listening on, along with the process name holding...

Full guide →
beginner · docker · containers · disk · cleanup · devops · pruning

Docker Cleanup Bash Script — Reclaim Disk Space from Docker Garbage

A bash script that removes stopped containers, unused images, dangling volumes, and build cache from...

Full guide →
beginner · bash · loops · for · scripting · beginner

Bash For Loop Examples

A for loop over ls output splits filenames with spaces and skips files silently. Loop over a glob, r...

Full guide →
beginner · sed · text-processing · find-replace · scripting · sysadmin

Find and Replace in Files with sed (Without Corrupting Half Your Tree)

Find and replace text in files with sed: in-place edits, GNU vs macOS -i, word boundaries, capture g...

Full guide →
beginner · networking · ip · dns · curl · security

Find Your IP Address on Linux: Local, Public, Gateway, DNS, and MAC

A firewall rule built on the wrong IP locks you out. Find your local, public, gateway, DNS, and MAC...

Full guide →
beginner · environment · export · cron-ready · variables · error-handling

Bash Environment Variables: export, unset, Subshells, and Why Cron Can't See Yours

A variable you never exported is invisible to child processes, so the deploy reads an empty token an...

Full guide →

Intermediate Scripts (30)

intermediate · cleanup · find · cron-ready

Delete Old Log Files

Unmanaged logs fill /var/log until writes fail and services crash. find -mtime deletes .log files ol...

Full guide →
intermediate · error-handling · best-practices · set

Bash Error Handling with set -euo pipefail

Bash keeps going after a failed command, so a broken cd followed by rm -rf hits the wrong directory....

Full guide →
intermediate · process · pkill · pgrep

Kill a Process with pkill and pgrep

ps, grep, copy the PID, kill: four steps every time. pkill stops a process by name in one command, a...

Full guide →
intermediate · chmod · security · find

File Permissions Security Audit

A world-writable file on a web server lets a compromised script overwrite your app. Audit permission...

Full guide →
intermediate · monitor · system · awk

Monitor CPU and RAM Usage

A runaway process at 100% CPU goes unnoticed until the server stops responding. Measure CPU and RAM...

Full guide →
intermediate · email · alert · mailx

Send Email Alerts from Bash

A monitoring script with no email alert fails silently until users notice. A reusable bash alert fun...

Full guide →
intermediate · mysql · backup · cron-ready

MySQL Database Backup Script

A mistaken DROP TABLE has no undo. Back up MySQL nightly with mysqldump and gzip, rotate dumps older...

Full guide →
intermediate · ssh · security · keys

SSH Key Setup Script

Password SSH on an internet-facing server invites brute-force attempts. A bash script runs ssh-keyge...

Full guide →
intermediate · files · disk · find · awk

Find Duplicate Files in Linux

Duplicate files pile up in archives and downloads and waste gigabytes. md5sum hashes every file and...

Full guide →
intermediate · systemd · monitor · cron-ready

Restart a Service If It Stopped

A crashed nginx or PostgreSQL stays down for hours with no watchdog. A cron script uses systemctl is...

Full guide →
intermediate · rsync · backup · ssh · cron · offsite · devops

Rsync Remote Backup

A local-only backup dies with the machine. Push an incremental, resumable copy to a remote server wi...

Full guide →
intermediate · ssl · openssl · security · monitoring · cron · networking

Check SSL Certificate Expiry with Bash

A bash script that connects to any domain over TLS, reads the certificate, and tells you how many da...

Full guide →
intermediate · bash · read · loops · files · intermediate

Read a File Line by Line in Bash

A while-read loop dropped the last server in a list: the file had no final newline. Read files line...

Full guide →
intermediate · bash · functions · arguments · scripting · intermediate

Bash Functions and Arguments

A function reused 'target' without local, overwrote the caller's variable, and cleanup deleted the w...

Full guide →
intermediate · bash · functions · scripting · local-scope

Bash Functions: Return Values, Local Scope, and Reusable Logic

return in a bash function sets an exit code, not a string. Return data with echo and command substit...

Full guide →
intermediate · bash · arrays · associative-arrays · scripting

Bash Arrays: Indexed, Associative, Append, and Safe Iteration

A list stored as a space-separated string splits once an item has a space. Bash arrays fix it: index...

Full guide →
intermediate · bash · arguments · getopts · cli

Bash Argument Parsing: Positional Args, getopts, and Long Flags

A script that reads $1 as a value takes --env as that value and deploys nowhere. Parse arguments wit...

Full guide →
intermediate · bash · strings · parameter-expansion · scripting

Bash String Manipulation: Substrings, Replace, and Parameter Expansion

cut -d/ -f3 returns the wrong slice once a URL gains https. Bash parameter expansion: substrings, pr...

Full guide →
intermediate · flock · cron · locking · concurrency · sysadmin

Prevent Overlapping Cron Jobs with flock

A long cron job overlaps its next run and stacks copies until the box falls over. flock locks it to...

Full guide →
intermediate · timeout · cron · signals · hang · sysadmin

Stop a Hung Command with timeout

A hung cron job never exits, never frees its lock, and quietly stops the job running. Bound a comman...

Full guide →
intermediate · retry · backoff · resilience · devops · scripting

Retry a Command with Exponential Backoff in Bash

A deploy that dies on the first transient error costs a night of manual re-runs. Retry with exponent...

Full guide →
intermediate · bash · curl · api · http · devops

Make API Requests in Bash with curl (That Actually Fail When the API Does)

Plain curl exits 0 on an HTTP 500 and poisons everything downstream. A bash curl wrapper that checks...

Full guide →
intermediate · bash · jq · json · api · parsing

Parse JSON in Bash with jq (Stop Using grep and cut on API Responses)

Read fields from a JSON API response with jq, and the three things (-r, // defaults, -e) that keep t...

Full guide →
intermediate · bash · slack · webhook · alerting · devops

Send Slack Alerts from Bash with Incoming Webhooks (So Cron Jobs Stop Failing Silently)

Post failure alerts to Slack from bash with curl, a jq-built payload and an ERR trap, so a broken ba...

Full guide →
intermediate · trap · mktemp · cleanup · error-handling · cron-ready

Bash trap: Clean Up Temp Files on Exit (Even When the Script Dies)

A script that dies mid-run leaves temp files and half-written output behind. trap on EXIT with mktem...

Full guide →
intermediate · ssh · remote · automation · exit-codes · security

Run Commands on a Remote Server over SSH from Bash (One Host or Twenty)

An ssh loop that ignores exit codes reports done while three hosts never changed. Run one command or...

Full guide →
intermediate · ports · ss · security · audit · cron-ready

Audit Listening Ports and Alert on New Ones — Bash Script

A bash script that snapshots every listening TCP and UDP socket as CSV, diffs it against the previou...

Full guide →
intermediate · systemd · monitor · cron-ready · flock · watchdog

Service Watchdog: Check a systemd Unit and Restart It Once — Bash Script

A cron bash watchdog for systemd units: restarts a stopped service, probes a hung one, bounds start-...

Full guide →
intermediate · cleanup · find · cron-ready · retention · backup

Log Retention Cleanup: Keep the Newest N, Delete Older Than D Days — Bash Script

A logrotate alternative for directories it does not own: keep the newest N dated folders, delete the...

Full guide →
intermediate · library · error-handling · trap · cron-ready · strict-mode

bashlib Starter: 10 Bash Functions to Source Into Every Script

Every script re-invents strict mode, ERR traps, temp cleanup and a lock, or forgets one. Source ten...

Full guide →

Free Interactive Tools

Need a cron expression? chmod calculator?

12 browser-based bash tools — no install required

Browse All Tools →
PAID RESOURCE — $9

The Production Bash Toolkit

An operational script system + a 30-function shared library + a 52-page field guide. The production layer the free snippets don't cover.

Get the Toolkit →