Shell Scripting: From Commands to Automation Beginner 35 min
Lab overview

Shell Scripting: From Commands to Automation

35 min 4 checked steps Beginner
The situation

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.

By the end of this lab you will be able to
  • 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.

The steps
1
Your first scriptCreate a script that prints a greeting and some live system information.
2
Arguments and exit codesMake a script that takes a name, and fails properly when it doesn't get one.
3
Loops and conditionsWrite a health check that reports each service as UP or DOWN and returns a meaningful exit code.
4
A production clean-up scriptWrite a clean-up script that deletes only old .log files and validates its input.
How this lab works
  1. Press Start lab. You get your own Ubuntu machine on the right, just for you.
  2. Read each step. Commands with a ▶ Run button can be sent to the terminal in one click, but typing them yourself helps you remember.
  3. 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.
  4. Stuck? Open the hint. Nothing you do here can break anything real.
Step 1 of 4

Your first script

Objective

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:

bash
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:

bash
chmod +x /root/scripts/hello.sh
/root/scripts/hello.sh

hello.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.

Step 2 of 4

Arguments and exit codes

Objective

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:

bash
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:

bash
/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.

Step 3 of 4

Loops and conditions

Objective

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.

bash
cat /root/services.txt
ls /var/run/svc

Read a file line by line with while read, and test for a file with [ -f path ]:

bash
while read -r svc; do
  echo "checking $svc"
done < /root/services.txt

Write /root/scripts/check-services.sh that

  1. prints one line per service: nginx: UP or postgres: DOWN,
  2. exits 0 if every service is up, and 2 if 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:

text
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
text
#!/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 2
Step 4 of 4

A production clean-up script

Objective

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 pipefail at the top stops the script on the first error, on undefined variables and on failures inside pipes.
  • find DIR -name "*.log" -mtime +N finds files modified more than N days ago, and -delete removes them.

Write /root/scripts/cleanup-logs.sh that is called like

text
cleanup-logs.sh <directory> <days>

and that

  1. exits 1 with a usage message on stderr if it does not get exactly 2 arguments,
  2. exits 1 with an error on stderr if the directory does not exist,
  3. deletes only *.log files older than <days> days in that directory (other files stay),
  4. prints Deleted N files at the end.

Create some test data to try it:

bash
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-test

Expected 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.

Lab complete

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 0 means success. CI/CD tools, && chains and set -e all depend on it.
  • Errors and usage messages go to stderr (>&2) so they don't pollute output that other tools parse.
  • set -euo pipefail is 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.

root@devopsshack offline

Your Linux machine is ready to launch

Starting gives you a private Ubuntu server for up to 45 minutes. It is deleted when you finish.

Feedback