Your First Shell Script
Write and run Bash scripts with a shebang, arguments, exit codes, if tests and for loops, then schedule them to run automatically with cron.
Welcome back!
Step 1 of 14Learn
From commands to a script
Every Friday, Sofia backs up a project directory: she creates a dated archive, copies it to a backup folder and deletes archives older than 30 days. Three commands, typed by hand, every week, sometimes forgotten. A shell script turns them into one command she never has to remember.
A script is just a text file containing commands, run from top to bottom:
#!/bin/bash
# backup.sh - archive the project folder
src="$HOME/project"
dest="$HOME/backups"
mkdir -p "$dest"
tar -czf "$dest/project-$(date +%F).tar.gz" "$src"
echo "Backup written to $dest"The first line, #!/bin/bash, is the shebang. It tells the system which interpreter should run the file. Other lines starting with # are comments, ignored by Bash but valuable to the next person who reads the script, which is often you in six months.
To run it:
- Save it as
backup.sh. - Make it executable:
chmod +x backup.sh. - Run it with
./backup.sh.
Remember the "Permission denied" from the permissions lesson: forgetting step 2 is exactly that error. You can also run bash backup.sh, which doesn't need the execute bit, but making the file executable is the standard approach.
Step 2 of 14Practice · Diagram
Anatomy of backup.sh
Which part tells the system which interpreter should run the file?
Tap the shape that answers the question, then press Check.
- backup.sh
- #!/bin/bash
The shebang: which interpreter runs the file. Must be the very first line.
- # comments
Ignored by Bash, read by humans.
- src= and dest=
Variables, so paths are written once. No spaces around
=.- mkdir, tar
The same commands you would type by hand, run top to bottom.
- echo
Tells the person running it what happened.
Step 3 of 14Practice · Put in order
Put the steps for creating and running a new script in the correct order.
Drag the items, or use the arrow buttons, to put them in order.
- Add the commands and save the file
- Run it with ./hello.sh
- Make it executable with chmod +x hello.sh
- Write #!/bin/bash as the first line
- Create the file with nano hello.sh
Step 4 of 14Learn
Arguments and exit codes
Scripts become reusable when they accept arguments. Inside a script:
$1,$2,$3... are the first, second and third arguments.$#is the number of arguments.$@is all of them (use"$@"to keep each one intact).$0is the name of the script itself.
So ./backup.sh /srv/site sets $1 to /srv/site, and the script can write src="$1".
Every command also finishes with an exit code (exit status): 0 means success, and any other number, 1 to 255, means some kind of failure. The exit code of the last command is stored in $?:
$ ls /etc > /dev/null; echo $?
0
$ ls /nope 2> /dev/null; echo $?
2Exit codes drive two handy operators:
cmd1 && cmd2runscmd2only ifcmd1succeeded:mkdir build && cd build.cmd1 || cmd2runscmd2only ifcmd1failed:cd /srv/app || exit 1.
That last pattern is important. If cd fails and the script carries on, the next command, perhaps an rm, runs in the wrong directory. Ending your own scripts with exit 0 on success and exit 1 on errors lets other scripts and schedulers know what happened. Many people also put set -e near the top, which stops the script at the first failing command.
Step 5 of 14Practice · Choose one
A script is run as ./deploy.sh production v2.4 --dry-run. What is the value of $# inside it?
Step 6 of 14Practice · True or false
In mkdir /srv/data && echo "created", the message is printed even if mkdir fails.
Step 7 of 14Compare
Chaining commands: ; vs && vs ||
| Aspect | a ; b | a && b | a || b |
|---|---|---|---|
| b runs when | Always | a succeeded (exit 0) | a failed (non-zero) |
| Typical use | Unrelated commands | mkdir build && cd build | cd /srv/app || exit 1 |
| Protects against | Nothing | Continuing after a failure | Running on in the wrong place |
Step 8 of 14Learn
Making decisions with if
An if statement runs commands only when a condition is true. In Bash, the condition is actually a command, and "true" means it exited with 0. The usual test command is [ ... ] (with required spaces inside the brackets):
#!/bin/bash
if [ $# -lt 1 ]; then
echo "Usage: $0 <directory>"
exit 1
fi
if [ -d "$1" ]; then
echo "Backing up $1"
else
echo "Error: $1 is not a directory"
exit 2
fiCommon tests:
| Test | True when |
|---|---|
-f file | the file exists and is a regular file |
-d dir | the directory exists |
-z "$var" | the variable is empty |
"$a" = "$b" | two strings are equal |
$n -eq 5, -ne, -lt, -gt, -le, -ge | numeric comparisons |
The spaces matter: [ -d "$1" ] works, [-d "$1"] fails, because [ is a command name and needs to stand alone. Note that = compares text and -eq compares numbers; < and > inside single brackets are redirections, not comparisons. Bash also offers [[ ... ]], a safer version with extra features, which you will see in many modern scripts.
Step 9 of 14Note
Step 10 of 14Practice · Spot the mistake
This script should print an error and stop if no argument is given. Tap the two tokens that contain mistakes.
Step 11 of 14Learn
Loops and scheduling with cron
A for loop repeats commands for each item in a list, which is where scripts start saving real time:
for f in IMG_*.jpg; do
mv "$f" "italy-$f"
doneThat is Jordan's 400-photo rename from the first lesson: the glob expands to every matching file, and the loop body runs once per file with $f set to its name. Other common lists: for host in web1 web2 db1; do ping -c1 "$host"; done and for i in {1..5}; do echo "Run $i"; done. A while loop repeats as long as a condition is true, for example reading a file line by line with while read -r line; do ... done < list.txt.
To run a script automatically, use cron, the standard scheduler. Edit your schedule with crontab -e. Each line has five time fields followed by the command:
# min hour day-of-month month day-of-week command
30 2 * * 5 /home/sofia/bin/backup.sh >> /home/sofia/backup.log 2>&1This runs every Friday (day 5, where 0 is Sunday) at 02:30. A * means "every". */15 * * * * means every 15 minutes. Cron runs with a minimal environment, so use absolute paths in cron jobs and redirect output to a log, or you will never see the errors.
Step 12 of 14Practice · Diagram
Reading 30 2 * * 5 backup.sh
Five time fields, then the command. Tap each field.
Which field limits this job to Fridays?
Tap the shape that answers the question, then press Check.
- 30 2 5 /home/sofia/bin/backup.sh
- 30: minute
At minute 30 of the hour.
- 2: hour
2 a.m. (24-hour clock).
- *: day of month
Any day of the month.
- *: month
Every month.
- 5: day of week
0 is Sunday, so 5 is Friday.
- The command
Use an absolute path: cron has a minimal environment.
Step 13 of 14Practice · Match the pairs
Match each crontab time specification to when it runs.
Tap an answer, then tap the place where it belongs (or drag it there).
- 0 * * * *
- /10 * * *
- 30 2 * * *
- 0 9 * * 1
- 0 0 1 * *
Step 14 of 14Practice · What would you do?
What would you do?
Sofia's backup script works perfectly when she runs it by hand, but the cron job she added never produces an archive. The crontab line is 0 3 * * * backup.sh. What is the most likely fix?
Lesson complete!