A Practical Guide to Automating Repetitive Tasks with Bash Scripts
If you find yourself typing the same commands by hand every day, you can write that work once and automate it forever. That is exactly what Bash scripts are for: they gather multiple commands into a single file, add logic, and run whenever you want. This guide walks you through every essential step of writing a working automation script from scratch, with hands-on examples.
The Shebang: A Script's First Line
Every Bash script starts with a shebang line that names the interpreter. This line tells the system which program should run the file.
#!/usr/bin/env bash
Using #!/usr/bin/env bash is more portable than #!/bin/bash, because it automatically finds wherever bash lives on your PATH. Right after it, it is a good habit to add the following line, which makes your script safer:
#!/usr/bin/env bash
set -euo pipefail
-e: Stop the script if any command fails.-u: Error out if an undefined variable is used.-o pipefail: If any command in a pipe fails, the whole pipe is considered failed.
Variables and Command Substitution
When defining a variable, there must be no spaces around the equals sign. To use the value, prefix it with $.
name="MagmaNex"
echo "Hello $name"
To capture a command's output into a variable, use command substitution. The $( ... ) form is preferred:
today=$(date +%Y-%m-%d)
file_count=$(ls -1 | wc -l)
echo "On $today there are $file_count files"
Always use variables inside double quotes ("$file"). This prevents the classic bugs that occur with paths containing spaces.
Conditionals and Loops
The power of automation comes from a script's ability to make decisions. You build conditions with if:
if [[ -f "/etc/hosts" ]]; then
echo "File exists"
else
echo "File not found"
fi
Commonly used test operators:
-f file— is it a regular file?-d dir— is it a directory?-z "$str"— is the variable empty?"$a" == "$b"— are the two strings equal?
To perform the same operation across many items, use a for loop:
for log in /var/log/*.log; do
echo "Processing: $log"
gzip "$log"
done
To repeat as long as a condition holds, a while loop is the right tool:
counter=1
while [[ $counter -le 5 ]]; do
echo "Attempt $counter"
counter=$((counter + 1))
done
Arguments: $1, $@ and Friends
The way to make your script flexible is to let it accept arguments when it runs. Bash exposes these arguments through special variables:
$0— the script's own name$1,$2, ... — the first, second argument in order$@— all arguments (each one separate)$#— the number of arguments
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <directory>"
exit 1
fi
target="$1"
echo "Backing up files in $target..."
for file in "$target"/*; do
cp "$file" "$file.bak"
done
Here we check the argument count with $# and show a usage message if it is missing. exit 1 ends the script with an error code, which matters when it is called from other scripts.
A Few Handy One-Liners
Automation does not always require long scripts. Here are some one-liner examples that make daily life easier:
# Delete .tmp files older than 7 days
find . -name "*.tmp" -mtime +7 -delete
# The 10 directories taking up the most space
du -sh */ | sort -rh | head -n 10
# Replace text across all files in bulk
grep -rl "old_text" . | xargs sed -i 's/old_text/new_text/g'
# Spin up a quick HTTP server on the spot
python3 -m http.server 8000
Making the Script Executable
To run a script as ./script.sh, you need to give it execute permission. Use chmod for that:
chmod +x script.sh
./script.sh
You can also set permissions in numeric (octal) form. Each digit is the sum of read (4), write (2), and execute (1) permissions:
chmod 755 script.sh # owner: rwx, group: r-x, other: r-x
chmod 700 secret.sh # only the owner can do anything
If you struggle to picture the difference between 755 and 700, the chmod Calculator tool lets you instantly see which number maps to which permissions.
Scheduling with Cron
Your script is ready, but what if you want it to run automatically every night? This is where cron comes in. You edit your scheduled jobs with crontab -e. A cron line consists of five time fields followed by a command:
# minute hour day month day_of_week command
0 3 * * * /home/user/backup.sh
The line above runs the script every day at 03:00. A few common examples:
*/15 * * * * /opt/scripts/check.sh # every 15 minutes
0 0 * * 0 /opt/scripts/weekly.sh # every Sunday at midnight
30 8 1 * * /opt/scripts/monthly.sh # on the 1st of each month at 08:30
These sequences of stars and numbers can be confusing at first. To figure out exactly what an existing expression means, use the Crontab Explainer tool, and to build the right expression from scratch, use the Cron Expression Generator tool.
Wrapping Up
You now have all the pieces of an automation script: starting with a shebang, variables and command substitution, logic with conditionals and loops, flexibility with arguments, granting permission with chmod, and scheduling with cron. A good next step might be keeping junk files out of your repositories so they do not clutter your scripts; the .gitignore Generator tool makes that easy.
Start small: pick a single repetitive task you do by hand today and turn it into a script. Over time, these scripts grow into a small army of assistants quietly working for you.
All MagmaNex tools run entirely in your browser; none of your data is ever sent to a server.

