{"schemaVersion":"1.0","type":"TechArticle","types":["Article","TechArticle"],"slug":"bash-scripting-for-beginners-write-your-first-10-useful-scripts-pko8m","url":"https://zyvop.com/bash-scripting-for-beginners-write-your-first-10-useful-scripts-pko8m","title":"Bash Scripting for Beginners: Write Your First 10 Useful Scripts","subtitle":"Learn Bash scripting from scratch by building 10 practical scripts for backups, file organizing, monitoring, and automation, with clear explanations.","tldr":"Bash scripting turns repetitive terminal work into one-command automation. In this beginner guide you will learn the essentials, then build 10 useful scripts for backups, renaming files, disk alerts, log cleanup, site checks, and more, plus debugging tips and common mistakes to avoid.","keywords":["beginners","linux","automation","bash","Shell Scripting","DevOps"],"entities":["Arpan Singh","beginners","linux","automation","bash","Shell Scripting","DevOps","ZyVOP"],"keyTakeaways":["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."],"headings":["Why Learn Bash Scripting?","Part 1: The Building Blocks","Your first script","Variables","Arguments and user input","Conditionals","Loops","Functions","Exit codes and chaining","Start every script safely","Clean up after yourself","Part 2: Ten Useful Scripts","1. Timestamped backup","2. Batch rename files","3. Disk space alert","4. Clean old log files (with a dry run)","5. Website uptime check","6. Organize your Downloads folder","7. Project scaffold generator","8. Update every Git repository in a folder","9. Find the busiest visitors in a web server log","10. System health report (Linux)","Run Your Scripts Automatically with Cron","Debugging Your Scripts"],"outboundLinks":[],"contentText":"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.shTwo 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.sh because the current folder is not in your PATH. 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' fiThe tests you will use most: -f path is true if it is a regular file, -d path if it is a directory, -e path if 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, -ge compare numbers inside [[ ]] (( count &gt; 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 &lt; input.txtFunctions 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 &amp;&amp; echo 'Created' # run the second command only if the first succeeds cd /some/folder || exit 1 # run the second command only if the first failsYour 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-e stops the script when a command fails -u treats an unset variable as an error, which catches typos -o pipefail makes 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 errorsPart 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 &lt;folder&gt; [destination]\" &gt;&amp;2 exit 1 fi source_dir=$(cd \"$1\" &amp;&amp; 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 &gt;&amp;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 doneYou 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 &gt;= threshold )); then echo \"WARNING: disk usage is ${usage}% (threshold ${threshold}%)\" &gt;&amp;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 &lt;folder&gt; [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.\" fiYou 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 &lt;url&gt;}\" 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)\" &gt;&amp;2 exit 1 fiYou 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 &lt;project-name&gt;}\" mkdir -p \"$name\"/{src,tests,docs} cat &gt; \"$name/README.md\" &lt;&lt;EOF # $name Created on $(date +%F) EOF printf 'node_modules/\\n.env\\n*.log\\n' &gt; \"$name/.gitignore\" git -C \"$name\" init -q echo \"Project '$name' created.\"You will learn: brace expansion ({src,tests,docs}), here-documents (&lt;&lt;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 \"==&gt; $repo\" git -C \"$repo\" pull --ff-only || echo \" Skipped (could not fast-forward)\" fi doneYou 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 &lt;access.log&gt; [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 -rnYou 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 6You will learn: using a function to avoid repeating yourself. Redirect the output to a file (./report.sh &gt; 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 &gt;&gt; /home/alice/backup.log 2&gt;&amp;1That 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 &gt;&gt; file 2&gt;&amp;1 so 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 =. Write name='Alice', not name = 'Alice'. Unquoted variables. rm $file breaks on names with spaces. Write rm \"$file\". Forgetting chmod +x. If you see Permission denied, this is usually why. Windows line endings. An error like bad interpreter: /usr/bin/env: bash\\r means the file has \\r characters. Fix it with sed -i 's/\\r$//' script.sh or dos2unix script.sh. Running a Bash script with sh. sh script.sh ignores the shebang and may not support Bash features. Use ./script.sh or bash script.sh. Using cd without checking it worked. Write cd \"$dir\" || exit 1, so a failed cd does 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 bash and set -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 local inside functions. Comment on why, not what. Run shellcheck before you trust a script. Keep your personal scripts in ~/bin and add that folder to your PATH, 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.","contentHash":"sha256:8944902f473ac3c96fb47c8203725bfaf29aab793c7bc30cd5d52c1144548b63","authorName":"Arpan Singh","authorUrl":"https://zyvop.com/author/arpan","authorSameAs":[],"category":"DevOps","tags":["beginners","linux","automation","bash","Shell Scripting"],"audience":"Developers, software engineers, and students learning DevOps","tone":"Instructional, practical, code-first","readingTimeMinutes":8,"wordCount":2110,"faqs":null,"primaryTopic":"DevOps","publishedAt":"2026-12-01T05:29:06.116Z","updatedAt":"2026-12-01T05:29:06.116Z","canonicalUrl":"https://zyvop.com/bash-scripting-for-beginners-write-your-first-10-useful-scripts-pko8m"}