COMP 10024 – Shell Scripting (Week 8)

March 9, 2026 7:07 pm Published by

Shell Scripting

A shell script is essentially a text based file containing a sequence of UNIX commands. To the system, it is a method of writing a program that the shell interprets and executes line by line. While you can use many interpreters (like Python or Perl), we will focus on the Bourne Again Shell (bash).


1. Basic Mechanics: The Foundation

Every well-constructed shell script follows a few non-negotiable rules:

  • The Sh’bang (#!): This must be the absolute first line of your script. it tells the Kernel which interpreter to use to run the rest of the file.
  • Permissions: For a script to run, it must have executable permissions.
  • Comments (#): Use the hashtag symbol to document your code. The shell ignores everything on a line after a #.

To create and run your first script, follow this workflow:

  1. Create a file named HelloWorld.sh.
  2. Add the following code:
#!/bin/bash
# This is our first script
echo "Hi there, world!"
  1. Make it executable and run it:
chmod +x HelloWorld.sh
./HelloWorld.sh

2. Interacting with Users and Arguments

Scripts become dynamic when they can accept input. There are two primary ways to do this:

A. User Input (read)

The read command captures what a user types into a variable. You can use echo -n to keep the cursor on the same line for a cleaner look.

B. Command Line Arguments

When you run a script with extra words (like ./script.sh arg1 arg2), the shell automatically populates special variables:

Variable Meaning
$0 The name of the script itself.
$1, $2... The first, second, etc., arguments passed.
$# The total number of arguments.
$@ or $* All arguments combined into a single string.

3. Logic and Flow Control

Logic allows your script to make decisions. The if statement evaluates a condition. If it is true, the then block runs; otherwise, the else block runs.

Crucial Rule: Always wrap your variables in double quotes when testing them. This prevents errors if a variable happens to be empty.

Common Test Operators:

  • = : Tests if two strings are equal.
  • -e : Tests if a file or directory exists.
  • -d : Tests specifically if a path is a directory.
  • -f : Tests if it is a regular file.

4. Looping and Functions

Loops allow you to repeat tasks without writing more code.

  • For Loops: Best for iterating over a known list of items (like files or names).
  • While Loops: Best for repeating a task as long as a condition remains true.

Functions are blocks of code you define once and call multiple times. This keeps your scripts clean and avoids repetition.

function greet {
    echo "Hello, $1!"
}

greet "Alice"
greet "Bob"

5. The Exit Status ($?)

Every command returns an exit code (0 for success, non-zero for failure). In Bash, the special variable $? always contains the exit code of the last command executed. You can set your own exit code using the exit command.


Practice Lab: The Scripting Sandbox

Follow these steps to build a functional interactive script that manages files.

Task 1: The Interactive Greeter

  1. Create lab_script.sh and add the sh’bang.
  2. Use echo -n to ask for the user’s name and read to store it.
  3. Output a personalized greeting.

Task 2: Argument Validation

  1. Modify the script to check if the user provided an argument.
  2. Use if [ $# -eq 0 ] to check the argument count.
  3. If they didn’t provide one, exit the script with an error code: exit 1.

Task 3: File Checker

  1. Take the first argument ($1) and check if it exists as a directory.
  2. If it exists, list the files inside.
  3. If it does not exist, print an error message.

Task 4: The Loop Challenge

  1. Create a loop that prints the numbers 1 through 5 using a while loop.
  2. Create a second loop that iterates through a list of colors (red, green, blue) and prints each one using a for loop.

Final Summary of Design Advice

  • Don’t be shy with comments: Future you will thank you.
  • Check for invalid input: Assume users will try to break your script.
  • Check return codes: Always ensure a command succeeded before moving to the next step.

Categorised in: ,

This post was written by amax

Comments are closed here.