
Why Learn Bash Scripting?
If you have ever typed the same five commands every morning, copied files by hand into dated folders, or checked a server's disk space one more time, you have found a job for a Bash script.
A Bash script is just a text file of terminal commands, plus a little logic: variables, conditions, and loops. Once you can write one, repetitive work becomes a single command, and often something that runs on its own while you do something else.
This guide has two parts. First, a fast tour of the building blocks. Then ten practical scripts you can copy, run, and modify. You do not need any programming background, only a terminal and a text editor.
Before you start: the examples work on Linux and macOS. A few commands (such as free and ps --sort) are Linux-specific, and I will point those out.
Part 1: The Building Blocks
Your first script
Create a file called hello.sh:
#!/usr/bin/env bash
echo 'Hello, world!'
Make it executable and run it:
chmod +x hello.sh
./hello.sh
Two things to notice:
The first line,
#!/usr/bin/env bash, is called the shebang. It tells the system which program should run the file.You type
./hello.shbecause the current folder is not in yourPATH. The./means "this folder".
Variables
name='Alice' # no spaces around the = sign
echo "Hello, $name" # double quotes expand variables
echo 'Hello, $name' # single quotes print exactly what you typed
today=$(date +%F) # command substitution: store a command's output
echo "Today is $today"
The most common beginner error is putting spaces around =. name = 'Alice' fails, because Bash thinks name is a command.
Arguments and user input
Arguments are what you type after the script name.
#!/usr/bin/env bash
echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Arg count: $#"
Run ./args.sh apple banana to see each value. To ask the user a question while the script runs:
read -rp 'What is your name? ' name
echo "Nice to meet you, $name"
Conditionals
if [[ -f "$file" ]]; then
echo 'It is a file'
elif [[ -d "$file" ]]; then
echo 'It is a directory'
else
echo 'Not found'
fi
The tests you will use most:
-f pathis true if it is a regular file,-d pathif it is a directory,-e pathif anything exists there-z "$s"is true if the string is empty,-n "$s"if it is not"$a" == "$b"compares strings-eq,-ne,-lt,-le,-gt,-gecompare numbers inside[[ ]](( count > 5 ))is a cleaner way to compare numbers
Prefer double brackets [[ ]] over single brackets [ ]. They are safer and more capable.
Loops
# Loop over files
for file in *.txt; do
echo "Processing $file"
done
# Loop over a range
for i in {1..5}; do
echo "Number $i"
done
# Loop while a condition is true
count=1
while [[ $count -le 3 ]]; do
echo "Count: $count"
count=$((count + 1))
done
# Read a file line by line
while IFS= read -r line; do
echo "Line: $line"
done < input.txt
Functions
greet() {
local name="$1" # 'local' keeps the variable inside the function
echo "Hello, $name"
}
greet 'Alice'
greet 'Bob'
Exit codes and chaining
Every command returns an exit code: 0 means success, anything else means failure. Check the last one with $?.
ls /nonexistent
echo $? # prints 2 (failure)
mkdir backup && echo 'Created' # run the second command only if the first succeeds
cd /some/folder || exit 1 # run the second command only if the first fails
Your own scripts should follow the same convention: exit 0 for success, exit 1 (or another non-zero number) for failure.
Start every script safely
Add this line near the top of most scripts:
set -euo pipefail
-estops the script when a command fails-utreats an unset variable as an error, which catches typos-o pipefailmakes a pipeline fail if any command in it fails
These are not magic, and there are edge cases, but they turn silent mistakes into loud ones, which is exactly what you want while learning.
Clean up after yourself
tmp=$(mktemp -d) # create a temporary folder
trap 'rm -rf "$tmp"' EXIT # delete it when the script ends, even on errors
Part 2: Ten Useful Scripts
Save each one as a .sh file, run chmod +x on it, and try it on a test folder first.
1. Timestamped backup
Compress a folder into a dated archive.
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <folder> [destination]" >&2
exit 1
fi
source_dir=$(cd "$1" && pwd) # turn it into an absolute path
dest_dir="${2:-$HOME/backups}" # default to ~/backups if no 2nd argument
name=$(basename "$source_dir")
parent=$(dirname "$source_dir")
timestamp=$(date +%F_%H-%M-%S)
archive="$dest_dir/${name}_${timestamp}.tar.gz"
mkdir -p "$dest_dir"
tar -czf "$archive" -C "$parent" "$name"
echo "Backup created: $archive"
You will learn: argument checking with $#, default values with ${2:-default}, and sending errors to stderr with >&2.
2. Batch rename files
Rename every .jpeg file in the current folder to .jpg.
#!/usr/bin/env bash
set -euo pipefail
for file in *.jpeg; do
[[ -e "$file" ]] || continue # skip if nothing matches the pattern
mv -n -- "$file" "${file%.jpeg}.jpg" # -n never overwrites an existing file
done
You will learn: ${file%.jpeg} removes a suffix from a variable. Before running any bulk rename, put echo in front of mv to preview what would happen.
3. Disk space alert
Warn when the root filesystem is getting full.
#!/usr/bin/env bash
set -euo pipefail
threshold="${1:-80}"
usage=$(df -P / | awk 'NR==2 {print $5}' | tr -d '%')
if (( usage >= threshold )); then
echo "WARNING: disk usage is ${usage}% (threshold ${threshold}%)" >&2
exit 1
fi
echo "Disk usage OK: ${usage}%"
You will learn: capturing command output, arithmetic comparison with (( )), and using exit codes so other tools (like cron or monitoring) can react.
4. Clean old log files (with a dry run)
A script that deletes things should show you what it will delete first.
#!/usr/bin/env bash
set -euo pipefail
log_dir="${1:?Usage: $0 <folder> [days] [--delete]}"
days="${2:-30}"
mode="${3:-}"
if [[ "$mode" == '--delete' ]]; then
find "$log_dir" -type f -name '*.log' -mtime +"$days" -print -delete
else
echo "Dry run. Log files older than $days days:"
find "$log_dir" -type f -name '*.log' -mtime +"$days" -print
echo "Run again with --delete to remove them."
fi
You will learn: the ${1:?message} pattern for required arguments, and the dry-run habit that prevents expensive accidents.
5. Website uptime check
#!/usr/bin/env bash
set -u
url="${1:?Usage: $0 <url>}"
status=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 "$url" || true)
if [[ "$status" =~ ^[23][0-9]{2}$ ]]; then
echo "UP: $url (HTTP $status)"
else
echo "DOWN: $url (HTTP $status)" >&2
exit 1
fi
You will learn: regular-expression matching with =~, and handling a command that is allowed to fail with || true. Extend it by looping over a list of URLs stored in a text file.
6. Organize your Downloads folder
Sort files into subfolders by type.
#!/usr/bin/env bash
set -euo pipefail
shopt -s nocasematch # treat JPG and jpg the same
target="${1:-$HOME/Downloads}"
for file in "$target"/*; do
[[ -f "$file" ]] || continue
case "${file##*.}" in
jpg|jpeg|png|gif|webp) folder='Images' ;;
pdf|doc|docx|txt|md) folder='Documents' ;;
mp4|mkv|mov|avi) folder='Videos' ;;
mp3|wav|flac) folder='Music' ;;
zip|tar|gz|7z) folder='Archives' ;;
*) folder='Other' ;;
esac
mkdir -p "$target/$folder"
mv -n -- "$file" "$target/$folder/"
done
echo "Organized: $target"
You will learn: the case statement, and ${file##*.}, which keeps only the part after the last dot.
7. Project scaffold generator
Create a new project folder with the structure you always want.
#!/usr/bin/env bash
set -euo pipefail
name="${1:?Usage: $0 <project-name>}"
mkdir -p "$name"/{src,tests,docs}
cat > "$name/README.md" <<EOF
# $name
Created on $(date +%F)
EOF
printf 'node_modules/\n.env\n*.log\n' > "$name/.gitignore"
git -C "$name" init -q
echo "Project '$name' created."
You will learn: brace expansion ({src,tests,docs}), here-documents (<<EOF) that expand variables, and running Git in another folder with -C.
8. Update every Git repository in a folder
#!/usr/bin/env bash
set -uo pipefail # no -e on purpose: keep going if one repo fails
root="${1:-$HOME/projects}"
for repo in "$root"/*/; do
if [[ -d "$repo/.git" ]]; then
echo "==> $repo"
git -C "$repo" pull --ff-only || echo " Skipped (could not fast-forward)"
fi
done
You will learn: deciding when not to use set -e. Here we want the loop to continue past a failure, and we handle errors explicitly with ||.
9. Find the busiest visitors in a web server log
#!/usr/bin/env bash
set -u
log="${1:?Usage: $0 <access.log> [count]}"
count="${2:-10}"
echo "Top $count IP addresses:"
awk '{print $1}' "$log" | sort | uniq -c | sort -rn | head -n "$count"
echo
echo "HTTP status code summary:"
awk '{print $9}' "$log" | sort | uniq -c | sort -rn
You will learn: chaining small tools with pipes. We skip pipefail here because head closes the pipe early, which can make pipefail report a harmless failure. The column numbers assume the common Nginx and Apache log format.
10. System health report (Linux)
#!/usr/bin/env bash
set -u
section() {
printf '\n--- %s ---\n' "$1"
}
echo "System report for $(hostname) at $(date '+%F %T')"
section 'Uptime and load'
uptime
section 'Memory'
free -h
section 'Disk (root)'
df -h /
section 'Top 5 processes by CPU'
ps aux --sort=-%cpu | head -n 6
You will learn: using a function to avoid repeating yourself. Redirect the output to a file (./report.sh > report.txt) to keep a history.
Run Your Scripts Automatically with Cron
Cron runs commands on a schedule. Open your schedule with crontab -e and add a line:
# minute hour day-of-month month day-of-week command
30 2 * * * /home/alice/scripts/backup.sh /home/alice/projects >> /home/alice/backup.log 2>&1
That runs the backup every day at 2:30 AM and appends all output to a log file. Two tips:
Always use absolute paths in cron jobs, since cron does not have your usual environment.
Redirect output with
>> file 2>&1so you can see what went wrong later.
Debugging Your Scripts
bash -n script.sh # check syntax without running anything
bash -x script.sh # run and print every command as it executes
shellcheck script.sh # lint for common mistakes (install it, it is worth it)
Inside a script, set -x turns tracing on and set +x turns it off, so you can focus on one suspicious section.
Common Beginner Mistakes
Spaces around
=. Writename='Alice', notname = 'Alice'.Unquoted variables.
rm $filebreaks on names with spaces. Writerm "$file".Forgetting
chmod +x. If you seePermission denied, this is usually why.Windows line endings. An error like
bad interpreter: /usr/bin/env: bash\rmeans the file has\rcharacters. Fix it withsed -i 's/\r$//' script.shordos2unix script.sh.Running a Bash script with
sh.sh script.shignores the shebang and may not support Bash features. Use./script.shorbash script.sh.Using
cdwithout checking it worked. Writecd "$dir" || exit 1, so a failedcddoes not cause the next command to run in the wrong place.Using
[ ]and getting strange errors. Switch to[[ ]].
Habits of Good Scripts
Start with
#!/usr/bin/env bashandset -euo pipefail(and know when to relax it).Print a usage message when arguments are missing.
Add a dry-run mode to anything that deletes or overwrites.
Quote your variables, always.
Use
localinside functions.Comment on why, not what.
Run
shellcheckbefore you trust a script.Keep your personal scripts in
~/binand add that folder to yourPATH, so you can run them from anywhere.
When to Switch to Another Language
Bash is excellent for gluing commands together, working with files, and automating system tasks. When a script grows past a couple hundred lines, needs to parse JSON, or has complicated data structures, a language like Python is usually easier to maintain. Starting in Bash is still the fastest way to automate the small things.
Final Thoughts
Scripting is a skill you build by solving your own small annoyances. Pick one task you did by hand this week, such as renaming a batch of files, checking a service, or backing up a folder, and turn it into a script. Start with the version that works, then add the usage message, the dry run, and the safety checks.
Try modifying one of the ten scripts above to fit your own workflow. That is how a tutorial turns into real skill.
Published via ZyVOP — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.
About the author
- One platform to write, cross-post to Dev.to, Medium, WordPress, Hashnode, and Bluesky, and protect your SEO with canonical links. Zero paywalls and full content ownership.
Comments
Join the discussionNo comments yet. Be the first to comment.





