Classroom Public page

Week 9: Linux Shell II

916 words

Scripting, environment, and remote access. A bash script is a text file of shell commands; the shell runs them in sequence. Environment variables configure programs without editing their code. SSH connects you to a remote machine as if you were sitting at it.


Theme

Week 8 was interactive: you typed commands one at a time and saw the results. Week 9 makes those commands repeatable: you save them to a script file, give the script a name, and run it whenever you need it. This is the foundation of automation.

By the end of week 9 you can write a 15-line bash script that takes an argument, processes a file, and produces output. You can explain what PATH and HOME mean. And you can open a shell on a remote machine with SSH.

Reading list (~1 hour)

  1. linuxcommand.org, lessons 7-10 (I/O redirection, expansion, permissions, job control)
  2. Bash Guide for Beginners at https://tldp.org/LDP/Bash-Beginners-Guide/html/, Chapters 1-4 (intro, variables, scripts, conditionals)
  3. Optional: man bash (the full manual; overwhelming; use it as a reference, not reading)

Lecture outline (~2 hours)

Section 1: Shell scripts

  • A shell script is a text file whose first line is a "shebang": #!/bin/bash or #!/usr/bin/env bash
  • The shebang tells the OS which interpreter to use; without it, the file is just text
  • Make the script executable: chmod +x my_script.sh
  • Run it: ./my_script.sh or bash my_script.sh
  • The script runs each line as a command; it is exactly like typing each line interactively, but automated

Section 2: Variables in bash

  • Assignment: name="Alice" (no spaces around =)
  • Reference: echo "$name" or echo "${name}"
  • Single quotes suppress variable expansion: echo '$name' prints $name literally
  • Double quotes allow expansion but protect spaces: echo "Hello, $name!"
  • Command substitution: result=$(ls -la | wc -l) runs the command and stores the output in result
  • Arithmetic: x=$((5 + 3)) uses arithmetic expansion; use $((...)) for integer math

Section 3: Positional parameters and arguments

  • A script can accept arguments: ./script.sh foo bar
  • Inside the script: $1 is the first argument ("foo"), $2 is the second ("bar"), $0 is the script name
  • $# is the number of arguments; $@ is all arguments as separate words
  • Always quote "$1" to handle arguments with spaces

Section 4: Conditionals

if [ "$1" = "hello" ]; then
    echo "You said hello"
elif [ "$1" = "bye" ]; then
    echo "Goodbye"
else
    echo "I do not recognize that"
fi
  • [ ... ] is the test command; spaces inside brackets are required
  • String tests: = (equal), != (not equal), -z (empty string), -n (non-empty)
  • File tests: -f file (file exists and is regular), -d dir (directory exists), -r file (readable)
  • Numeric tests: -eq, -ne, -lt, -le, -gt, -ge

Section 5: Loops

for i in 1 2 3 4 5; do
    echo "Number: $i"
done
while [ "$count" -lt 10 ]; do
    echo "$count"
    count=$((count + 1))
done

The for loop iterates over a list; while loops as long as a condition is true.

Section 6: Environment variables

  • Environment variables are named values the shell passes to every program it starts
  • View all: env or printenv
  • Common ones:
    • PATH: colon-separated list of directories where the shell looks for commands. Run echo $PATH.
    • HOME: your home directory
    • USER: your username
    • SHELL: path to your shell binary
    • EDITOR: your preferred text editor (used by git, cron, etc.)
  • Set a variable for the current session: export MY_VAR="value" (the export makes it visible to child processes)
  • Set permanently: add export MY_VAR="value" to ~/.bashrc or ~/.zshrc

Section 7: SSH

  • SSH (Secure Shell) opens an encrypted connection to a remote machine and gives you a shell there
  • Basic usage: ssh username@hostname or ssh username@192.168.1.100
  • Key-based authentication: instead of typing a password, you use a keypair. ssh-keygen -t ed25519 generates a keypair; the public key goes on the server in ~/.ssh/authorized_keys; the private key stays on your machine
  • scp source user@host:dest: copy files over SSH (like cp but across a network)
  • ssh -L 8080:localhost:3000 user@host: port forwarding (preview; useful in security courses)
  • In this course: SSH to the academy lab server (if provided) or to a local VM

Labs (~90 minutes)

Lab 9.1: Bash Script (labs/lab-9-1-bash-script.md)

  • Write a script analyze.sh that takes a filename as $1, checks that the file exists, counts its lines and words, and prints a summary
  • The script must handle the case where no argument is given (print usage and exit)
  • Artifact: analyze.sh committed to Git; screenshot of it running on two different files

Independent practice (~4 hours)

  1. Extend analyze.sh: add a --count-errors flag that also counts lines containing the string "ERROR" (case-insensitive)
  2. Write a script that loops through all .txt files in a directory and prints their names and line counts
  3. Practice SSH: set up a local VM (VirtualBox or UTM on macOS) and SSH into it from your main machine using a keypair instead of a password
  4. Read man ssh_config and add a Host entry to ~/.ssh/config for a frequently-used server
  5. Explore crontab -e (the cron scheduler). Add a cron entry that runs a harmless script (e.g., date >> /tmp/heartbeat.log) every minute. Verify it works. Remove it after 5 minutes.

Reflection prompts (~30 minutes)

  1. Your analyze.sh script automates something you could do manually in 3 commands. At what point does writing a script stop being worth the effort? (There is no single right answer; reason it through.)
  2. The PATH variable determines where your shell looks for programs. What would happen if someone added a malicious directory to the front of your PATH? (Preview: this is a real attack class.)
  3. SSH uses public-key cryptography. You kept your private key and gave the server your public key. Why is it safe to give the server the public key? Why must you never share the private key?
  4. A shell script runs as your user; it can delete your files, connect to the internet, or modify configuration. This makes scripts powerful and dangerous. What practices would make your scripts safer?
  5. By the end of week 9, you can navigate the filesystem, search files, write scripts, and SSH to remote machines. In what part of computing would these skills be most immediately useful to you?

What comes next

Week 10 introduces Git: the version-control system. Git tracks changes to files over time, lets you collaborate with others, and gives you an "undo" history for your work. The shell skills from weeks 8-9 are all you need; Git is driven entirely from the command line.