Skip to content
$bash-snippets

Bash Script Library

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

68scripts
14free tools
0logins required

Beginner Scripts (30)

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 →
beginner · ports · ss · networking · troubleshooting · security

Port Is Listening but Connection Refused: Check the Bind Address — Bash Script

ss shows the port listening, yet other machines get Connection refused. The service is bound to 127....

Full guide →
beginner · systemd · journald · disk · logs · cron-ready

journalctl Disk Usage: Check and Limit the systemd Journal Size — Bash Script

The systemd journal keeps logs until its own cap, up to 4G by default. Check it with journalctl --di...

Full guide →
beginner · crlf · shellcheck · git · troubleshooting · sed

/bin/bash^M: bad interpreter — Fix CRLF Line Endings in Bash Scripts

/bin/bash^M: bad interpreter means the script has Windows CRLF line endings. Find them with file or...

Full guide →
beginner · path · troubleshooting · exit-codes · cron · crlf

Fix "bash: command not found": PATH, Typos, hash -r, CRLF and Cron

Fix bash: command not found: check PATH, typos, a stale hash table, CRLF line endings and sudo's PAT...

Full guide →
beginner · shellcheck · troubleshooting · test · quoting · error-handling

Fix "unary operator expected" in Bash: Empty Variables in [ ]

Fix bash unary operator expected errors: an empty variable inside [ ] vanishes. Quote it, switch to...

Full guide →
beginner · permissions · troubleshooting · exit-codes · chmod · security

Fix "Permission denied" in Bash: chmod, noexec, Directories and Exit 126

Fix Permission denied when running a bash script: chmod +x, directory search bits, noexec mounts and...

Full guide →
beginner · networking · ss · ports · netstat · troubleshooting

ss Command Examples: -tulpn, Port Filters and What Each Column Means

Copy-paste ss command examples: -tulpn, port and state filters, -s, and the netstat equivalents, wit...

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

Remove All Docker Containers Safely: Stopped, Running, Filtered

Remove all Docker containers in two commands, plus the filters, the empty-list error, what survives...

Full guide →
beginner · awk · text-processing · logs · csv · one-liners

AWK Cheat Sheet: Print Columns, Filter Rows, Sum and Count (Run-Verified)

AWK cheat sheet with run-verified one-liners: print a column, filter rows, sum a field, count by key...

Full guide →
beginner · loops · read · bash · error-handling · cron-ready

Bash While Loop Examples: read -r, the Pipe Subshell Trap, until and Timeouts

Bash while loop examples that survive production: read -r line loops, the pipe-subshell variable tra...

Full guide →
beginner · case · bash · patterns · glob · control-flow

Bash Case Statement Examples: Patterns, Order, ;;& and ;& Fallthrough

Bash case statement examples with real output: glob patterns, | alternatives, why pattern order matt...

Full guide →
beginner · scp · ssh · file-transfer · exit-codes · automation

scp Command Examples for Scripts: Push, Pull, Spaces, -O and Exit Codes

scp command examples run for real: push, pull, -r, -p, remote paths with spaces, OpenSSH 9+ SFTP mod...

Full guide →
beginner · cron · troubleshooting · cron-ready · path · logs

Cron Job Not Running? 7 Checks That Find the Cause

Cron job not running? Seven checks in order: the daemon, the schedule, permissions, cron's PATH, une...

Full guide →
beginner · ubuntu · coreutils · uutils · upgrade · troubleshooting

Ubuntu 26.04 Rust Coreutils: Check Which One You Run and Switch Back to GNU

Ubuntu 26.04 runs most coreutils from Rust (uutils) but keeps cp, mv and rm GNU. See which one each...

Full guide →
beginner · systemd · troubleshooting · services · exit-codes · linux

Fix systemd "status=203/EXEC": Five Causes and How to Tell Them Apart

status=203/EXEC means systemd could not start your program at all. The journal line names which of f...

Full guide →

Intermediate Scripts (38)

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 silently skips the last line of a file with no final newline. Read files line by l...

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 →
intermediate · disk · inodes · df · troubleshooting · cron-ready

No Space Left on Device but df Shows Free Space: Out of Inodes — Bash Script

Writes fail with No space left on device while df -h shows free space: the filesystem is out of inod...

Full guide →
intermediate · find · xargs · cleanup · troubleshooting · cron-ready

Argument List Too Long: Delete or Move Thousands of Files in Bash

rm *.log fails with Argument list too long and deletes nothing: the glob outgrew ARG_MAX. Use find -...

Full guide →
intermediate · lsof · disk · ports · troubleshooting · processes

lsof Command Examples: Ports, Open Files and Deleted Files Eating Your Disk

lsof examples for three real jobs: which process holds a port, who has a file or directory open, and...

Full guide →
intermediate · heredoc · bash · quoting · config · ssh

Bash Heredoc: <<EOF, Quoted 'EOF', <<- Indentation and Here-Strings

Bash heredoc explained with real runs: quoted vs unquoted EOF and what expands, <<- and the tabs-onl...

Full guide →
intermediate · sudo · ubuntu · sudoers · security · troubleshooting

Fix sudo-rs "wildcards are not allowed in command arguments" on Ubuntu 26.04

Ubuntu 26.04's sudo-rs drops sudoers rules with wildcards in arguments, then denies the command. See...

Full guide →
intermediate · sudo · ubuntu · sudoers · troubleshooting · security

Fix sudo-rs "I'm sorry user. I'm afraid I can't do that" on Ubuntu 26.04

sudo-rs on Ubuntu 26.04 says I'm afraid I can't do that for a missing rule, a dropped rule or one wr...

Full guide →
intermediate · ubuntu · coreutils · uutils · exit-codes · troubleshooting

Rust Coreutils vs GNU: The Differences That Break Bash Scripts on Ubuntu 26.04

Ubuntu 26.04's Rust coreutils change timeout's exit code, error text and edge cases scripts rely on....

Full guide →
intermediate · systemd · troubleshooting · services · restart · linux

Fix systemd "Start request repeated too quickly" (start-limit-hit)

Start request repeated too quickly means systemd stopped restarting a crashing service. Find the err...

Full guide →

Free Interactive Tools

Need a cron expression? chmod calculator?

14 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 →