Shell Scripting: From Commands to Automation
Your team runs the same checks and clean-ups by hand on every server, every week. Your lead asks you to turn them into scripts: a health check that the monitoring system can run, and a log clean-up that stops disks from filling up.
- Write and run a Bash script with a proper shebang
- Use arguments, exit codes and stderr the way CI pipelines expect
- Read a file line by line and make decisions with if and loops
- Write a safe, production-style clean-up script with set -euo pipefail
What you need to know first. A Bash script is a text file of commands that run top to bottom, exactly as if you typed them. You will write four scripts in /root/scripts, and each check runs your script with test inputs, so it has to really work, not just exist.
To edit files use nano (save with Ctrl+O then Enter, exit with Ctrl+X) or vim if you prefer. You can also create a whole file in one go with a heredoc, as the steps show. shellcheck script.sh is installed and points out common mistakes.
- Press Start lab. You get your own Ubuntu machine on the right, just for you.
- Read each step. Commands with a ▶ Run button can be sent to the terminal in one click, but typing them yourself helps you remember.
- Do the Your task part, then press Check my work. The check looks at the machine and tells you what is right or still missing.
- Stuck? Open the hint. Nothing you do here can break anything real.
Your first script
Create a script that prints a greeting and some live system information.
Why we do this: Any command we type more than twice ends up in a script. Scripts run our health checks, backups and deployment steps, and almost every CI pipeline step is a small shell script.
A script is a text file of commands. The first line, the shebang, tells Linux which interpreter runs it.
Create /root/scripts/hello.sh:
cat > /root/scripts/hello.sh <<'EOF'
#!/bin/bash
echo "Hello, DevOps Shack"
echo "Today is $(date +%A)"
echo "This machine is $(hostname)"
EOF$(...) is command substitution: it runs a command and puts its output into the text.
Make it executable and run it:
chmod +x /root/scripts/hello.sh
/root/scripts/hello.shhello.sh must be executable and its first line of output must be exactly Hello, DevOps Shack.
Expected result: /root/scripts/hello.sh runs and its first line of output is exactly Hello, DevOps Shack.
Arguments and exit codes
Make a script that takes a name, and fails properly when it doesn't get one.
Why we do this: CI/CD tools decide whether a step passed only by its exit code. A script that prints an error but exits 0 lets a broken deployment continue, which is why we always exit with the right code.
Scripts receive arguments as $1, $2, …, and $# is how many were given. Every command also returns an exit code: 0 means success, anything else means failure. CI pipelines stop when a step exits non-zero, so good scripts exit with the right code.
Create /root/scripts/greet.sh:
cat > /root/scripts/greet.sh <<'EOF'
#!/bin/bash
if [ $# -lt 1 ]; then
echo "Usage: $0 <name>" >&2
exit 1
fi
echo "Hello, $1!"
EOF
chmod +x /root/scripts/greet.sh>&2 sends the usage message to stderr, where error messages belong.
Try it, and print the exit code with $? after each run:
/root/scripts/greet.sh Aditya; echo "exit code: $?"
/root/scripts/greet.sh; echo "exit code: $?"greet.sh NAME must print Hello, NAME! and exit 0. Without arguments it must print a usage message to stderr and exit 1.
Expected result: greet.sh Priya prints Hello, Priya! with exit code 0, and greet.sh alone prints a usage message and exits 1.
Loops and conditions
Write a health check that reports each service as UP or DOWN and returns a meaningful exit code.
Why we do this: Monitoring systems such as Nagios or simple cron checks run scripts like this one and alert on the exit code. Loops and conditions are what turn a list of commands into real automation.
Now a small health check. /root/services.txt lists services, one per line. A service is UP if /var/run/svc/<name>.pid exists.
cat /root/services.txt
ls /var/run/svcRead a file line by line with while read, and test for a file with [ -f path ]:
while read -r svc; do
echo "checking $svc"
done < /root/services.txtWrite /root/scripts/check-services.sh that
- prints one line per service:
nginx: UPorpostgres: DOWN, - exits
0if every service is up, and2if at least one is down.
The check also runs your script against a different services file, so read the file path from $1 if one is given, otherwise use /root/services.txt:
file="${1:-/root/services.txt}"Expected result: The script prints one UP or DOWN line per service and exits 2 here, because postgres is down.
Hint: full solution
#!/bin/bash
file="${1:-/root/services.txt}"
down=0
while read -r svc; do
[ -z "$svc" ] && continue
if [ -f "/var/run/svc/$svc.pid" ]; then
echo "$svc: UP"
else
echo "$svc: DOWN"
down=1
fi
done < "$file"
[ $down -eq 0 ] || exit 2A production clean-up script
Write a clean-up script that deletes only old .log files and validates its input.
Why we do this: Full disks caused by old logs wake people up at night. A small, safe clean-up script on a schedule prevents that, and set -euo pipefail makes sure it stops instead of doing damage when something unexpected happens.
Full disks caused by old logs are a classic on-call page. Write the script that prevents it.
Two habits from production scripts:
set -euo pipefailat the top stops the script on the first error, on undefined variables and on failures inside pipes.find DIR -name "*.log" -mtime +Nfinds files modified more than N days ago, and-deleteremoves them.
Write /root/scripts/cleanup-logs.sh that is called like
cleanup-logs.sh <directory> <days>and that
- exits
1with a usage message on stderr if it does not get exactly 2 arguments, - exits
1with an error on stderr if the directory does not exist, - deletes only
*.logfiles older than<days>days in that directory (other files stay), - prints
Deleted N filesat the end.
Create some test data to try it:
mkdir -p /tmp/logs-test
touch -d "10 days ago" /tmp/logs-test/old1.log /tmp/logs-test/old2.log
touch /tmp/logs-test/today.log
touch -d "10 days ago" /tmp/logs-test/keep.txt
ls -l /tmp/logs-testExpected result: cleanup-logs.sh /tmp/logs-test 7 deletes old1.log and old2.log, keeps today.log and keep.txt, and prints Deleted 2 files.
Hint: counting deleted files
find "$dir" -type f -name "*.log" -mtime +"$days" -print -delete | wc -l prints each deleted file and counts the lines.
Brilliant work!
You wrote four scripts that behave like real automation: they validate input, report errors properly and return meaningful exit codes.
Interview-ready takeaways:
- Exit code
0means success. CI/CD tools,&&chains andset -eall depend on it. - Errors and usage messages go to stderr (
>&2) so they don't pollute output that other tools parse. set -euo pipefailis the standard safety header for production scripts.${1:-default}gives a default value when an argument is missing.
Next: the Log Analysis on the Command Line lab.
Write real Bash scripts with arguments, exit codes, loops and conditions, ending with a log clean-up script like the ones running on production servers.
Your team runs the same checks and clean-ups by hand on every server, every week. Your lead asks you to turn them into scripts: a health check that the monitoring system can run, and a log clean-up that stops disks from filling up.