Linux & OS Basics Intermediate +250 XP

Shell Scripting

The Foundation: Shebang & Positional Parameters

A shell script is simply a text file containing a sequence of terminal commands that gets executed by a shell interpreter. To declare which interpreter to use, scripts start with a **Shebang** (#!) on line one:

#!/bin/bash
echo "Active interpreter: Bash"

Positional parameters allow you to pass external arguments into your automation scripts at runtime:

  • $0: The name of the script itself.
  • $1, $2: The first and second arguments passed to the script.
  • $#: The total number of arguments supplied.
  • $?: The exit code of the last executed command (0 is success, non-zero is failure).

Variables and Conditionals

Variables store strings or numbers. Declaring them is simple, but note that **no spaces** are allowed around the assignment operator:

# Correct variable definition
BACKUP_DIR="/var/log"

# Accessing variables requires a dollar prefix
echo "Target backup: $BACKUP_DIR"

Conditionals test states using square brackets. Ensure you keep spaces around the test expression:

if [ -z "$1" ]; then
  echo "[ERROR] Parameter missing!"
  exit 1
fi

Loops and Stream Redirection

Loops automate execution over collections of items (like folders or logs). The for loop is the most common pattern:

for file in *.log; do
  echo "Analyzing: $file"
  gzip "$file"
done

You can route inputs and outputs using standard redirections: > to overwrite, >> to append, and 2>&1 to merge error streams into normal output streams.