Linux & Docker · Lesson 4 of 7

Shell scripting basics

Variables, conditions, loops and exit codes to automate repetitive tasks.

A shell script saves a sequence of commands in a file so you can run them again — backups, log clean-up, deployment steps, health checks.

  • Start with #!/usr/bin/env bash and add set -euo pipefail so the script stops on errors.
  • Variables: NAME="value" (no spaces around =), used as "$NAME" — always quote them.
  • if, for and while work like other languages, with slightly different syntax.
  • Every command returns an exit code: 0 means success, anything else means failure. $? holds the last one.

Example in the terminal

Run these on your own computer
$ cat check_disk.sh
#!/usr/bin/env bash
set -euo pipefail

LIMIT=80
for mount in / /var; do
  used=$(df --output=pcent "$mount" | tail -1 | tr -dc '0-9')
  if [ "$used" -ge "$LIMIT" ]; then
    echo "WARNING: $mount is at $used% (limit $LIMIT%)"
  else
    echo "OK: $mount is at $used%"
  fi
done

$ chmod +x check_disk.sh
$ ./check_disk.sh
WARNING: / is at 95% (limit 80%)
OK: /var is at 41%

Lines starting with $ are commands you type; the rest is what the terminal prints. Use Linux, macOS, WSL on Windows or a free cloud shell. Names and paths are examples.

Key points

  • Scripts automate repeated command sequences.
  • Use set -euo pipefail to stop on errors.
  • Quote variables: "$NAME".
  • Exit code 0 = success; anything else = failure.

Quick check

What does an exit code of 0 mean?

Practice task

Write a script that takes a folder name as $1, counts the .log files in it and prints the total, exiting with code 1 if the folder doesn't exist.

Interview corner

What does set -e do in a shell script?

It makes the script exit as soon as any command fails, instead of continuing with bad state. Combined with -u (error on unset variables) and -o pipefail (fail if any part of a pipe fails), it makes scripts much safer.

How do you schedule a script to run daily?

Add a cron entry with crontab -e, for example 0 2 * * * /opt/scripts/backup.sh to run at 2 AM every day, or use a systemd timer.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.