Bash script examples
Bash scripts are plain text files that run Linux commands in a repeatable way. They are ideal for automating backups, deployments, and quick server checks. Below you will find copy-paste bash script examples with safe defaults and short explanations. You can run these on your laptop or on a server like a Middlehost VPS hosting plan.
What is a Bash script?
A Bash script is a file that starts with a shebang (usually #!/usr/bin/env bash) and contains commands Bash should execute. Bash is common on Linux servers and works great for glue tasks like file operations, calling APIs (via curl), and running scheduled jobs.
How to run a Bash script
You have two common options. If you are using shared hosting with cPanel, you will usually run scripts via Cron Jobs (scheduled tasks) from the panel.
- Run with Bash directly (no execute permission needed):
bash script.sh
- Make it executable and run it:
chmod +x script.sh ./script.sh
Tip: sh script.sh is not the same as bash script.sh. If your script uses Bash features (like [[ ... ]]), run it with bash.
A safe starter template (recommended)
This template enables safer behavior: it stops on errors, treats unset variables as errors, and fails pipelines properly. It also sets a clean IFS to reduce bugs when looping over strings.
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
log() { printf '[%s] %s\n' "$(date +'%Y-%m-%d %H:%M:%S')" "$*"
}
Before running any script on production, validate syntax:
bash -n script.sh
10 practical bash script examples
1) Hello world with variables
#!/usr/bin/env bash
set -euo pipefail
name="Middlehost"
echo "Hello, $name"
2) Accept command line arguments (with usage)
This pattern is useful for automation on servers where you want scripts to be non-interactive.
#!/usr/bin/env bash
set -euo pipefail
if [ "${1:-}" = "" ]; then echo "Usage: $0 " exit 1
fi
domain="$1"
echo "Checking: $domain"
3) Read user input safely
#!/usr/bin/env bash
set -euo pipefail
read -r -p "Enter your email: " email
echo "You entered: $email"
4) If conditions: file exists, directory exists
#!/usr/bin/env bash
set -euo pipefail
path="${1:-/etc/hosts}"
if [ -f "$path" ]; then echo "File exists: $path"
elif [ -d "$path" ]; then echo "Directory exists: $path"
else echo "Not found: $path"
fi
5) Loop over files in a directory
Use quoting to avoid issues with spaces in filenames.
#!/usr/bin/env bash
set -euo pipefail
dir="${1:-.}"
for file in "$dir"/*; do [ -e "$file" ] || continue echo "Found: $file"
done
6) Read a file line-by-line
#!/usr/bin/env bash
set -euo pipefail
list="${1:-domains.txt}"
if [ ! -f "$list" ]; then echo "Missing file: $list" exit 1
fi
while IFS= read -r line; do [ "$line" = "" ] && continue echo "Line: $line"
done < "$list"
7) Functions + basic error handling
#!/usr/bin/env bash
set -euo pipefail
die() { echo "Error: $*" 1>&2 exit 1
}
require_cmd() { command -v "$1" 1>/dev/null 2>&1 || die "Missing command: $1"
}
require_cmd curl
echo "curl is available"
8) Simple backup script (tar.gz with retention)
This is a common use case on Linux servers: create a dated backup archive and keep only the last N backups. If you are backing up a website, check your disk space and inode usage first.
#!/usr/bin/env bash
set -euo pipefail
src="${1:-/var/www}"
dest="${2:-$HOME/backups}"
keep="${3:-7}"
mkdir -p "$dest"
stamp="$(date +'%Y-%m-%d_%H%M%S')"
out="$dest/backup_$stamp.tar.gz"
tar -czf "$out" -C "$src" .
echo "Created: $out"
ls -1t "$dest"/backup_*.tar.gz 2>/dev/null | tail -n +"$((keep+1))" | while IFS= read -r old; do rm -f "$old"
done
9) Disk, RAM, and inode quick health check
On hosting servers, running out of disk space or inodes can break uploads, email, and backups. This script prints usage so you can alert on it in a cron job.
#!/usr/bin/env bash
set -euo pipefail
echo "Disk usage:"
df -h
echo
echo "Inode usage:"
df -ih
echo
echo "Memory usage:"
free -h 2>/dev/null || true
10) Run a daily cron job (example)
If you have cPanel hosting plans, you can schedule scripts under Cron Jobs. On a VPS, you can use crontab -e. This example runs a backup every day at 02:30.
30 2 * * * /bin/bash /home/user/backup.sh >> /home/user/backup.log 2>&1
When NOT to use Bash (and what to use instead)
Bash is perfect for small automation and server glue code. If your task grows into complex data structures, heavy parsing, or cross-platform logic, Bash becomes harder to maintain. In those cases, consider Python or a configuration tool (like Ansible) for reliability.
| Task | Good choice | Why |
|---|---|---|
| Quick automation on Linux (files, cron, logs) | Bash | Fast to write, already installed, easy to glue commands |
| Complex parsing, APIs, structured data | Python | Better libraries, safer string handling, testable code |
| Repeatable server setup across many machines | Ansible | Idempotent, inventory based, less custom scripting |
Common Bash scripting mistakes
- Not quoting variables: use
"$var"in most cases. - Using
shfor Bash scripts: if you wrote Bash, run it withbash. - Ignoring exit codes: enable
set -eor check return values. - Unclear inputs: show a usage message and validate arguments early.
FAQs
What is the best way to learn Bash scripting quickly?
Start by editing and running small scripts that do real work: file backups, log checks, and simple monitoring. Learn the basics first: variables, quoting, if statements, loops, and functions. Then add safe defaults like set -euo pipefail so mistakes fail early.
How do I make a Bash script executable?
Add a shebang on the first line (for example #!/usr/bin/env bash), then run chmod +x script.sh. After that you can execute it as ./script.sh. If you do not want to change permissions, you can always run it as bash script.sh.
Why does my script work in terminal but fail in cron?
Cron runs with a minimal environment: different PATH, no interactive shell, and different working directory. Use absolute paths to commands (or set PATH in the script), cd into the expected directory, and log output to a file so you can see errors and exit codes.
What does set -euo pipefail do in Bash?
set -e stops the script on errors, -u errors on unset variables, and pipefail makes a pipeline fail if any command in it fails. Together they prevent silent failures and reduce debugging time, especially on servers where a failed backup or deploy can waste CPU/RAM and disk.
Should I use Bash or Python for server automation?
Use Bash for small, command-focused tasks like backups, cron jobs, log rotation, and quick health checks. Use Python when you need complex parsing, structured data, API-heavy workflows, or unit tests. On production systems, the easiest code to maintain is often the code that is most readable six months later.
If you want to run these scripts on a Linux server with stable CPU and RAM resources, a cloud hosting plan or a VPS is usually the cleanest setup for automation.