The terminal and Unix basics¶
What you'll be able to do¶
- Move around a Unix filesystem and inspect files without guessing where you are.
- Combine small commands to answer a question about logs and detect failure from an exit code.
- Start, monitor, and safely stop work on your machine or a remote server.
Why a terminal is useful¶
A terminal gives you a text interface to a shell. The shell reads commands, starts programs, and connects their input and output. A command you can type can also go into a script, be repeated on another machine, or run as part of a test. That is why terminal work is easy to automate and reproduce. Git, Docker, and SSH are command-line tools, and remote servers often offer only a shell.
Commands run in a current working directory. Think of the filesystem as a tree: directories contain files and other directories. A path beginning with / is absolute, from the root. A path without / at the start is relative to where you are. . means here, .. means the parent, and ~ expands to your home directory in the shell.
From project, data and ./data name the same directory; ../project/train.py reaches the script through its parent. Your home path varies by system, so prefer ~ over guessing it.
pwd # print where you are
ls # list entries here
mkdir -p scratch/raw # create directories
cp train.py scratch/ # copy a file
mv scratch/train.py scratch/copy.py # move or rename
cd scratch
cd .. # go to the parent
rm scratch/copy.py # remove a file
Substitute an existing file for train.py if needed. rm normally has no undo: inspect the path before running it, especially with -r (recursive) or -f (force). Quote paths containing spaces: cd "my project".
Inspect before you load¶
The shell can answer small questions without opening an editor or loading a dataset. cat prints a small file; less lets you page through a large one (q quits). head and tail show the first and last lines; wc -l counts newline-terminated lines. tail -f keeps showing new lines as a log grows.
head -n 5 data.csv
tail -n 20 train.log
wc -l data.csv
grep -n 'ERROR' train.log
grep -rni 'timeout' logs/
find . -name '*.csv'
grep selects matching lines. -n prints line numbers, -r searches inside a directory tree, and -i ignores letter case. find searches file paths, such as CSV files anywhere below .. Use head to see a CSV's header and shape, and wc -l for a rough row count (subtract one for the header, if each row occupies one line).
Streams, pipes, and exit codes¶
Commands launched from a shell normally use three standard streams: stdin (input), stdout (normal output), and stderr (errors or diagnostics). A pipe, |, connects one command's stdout to the next command's stdin, not stderr. > writes stdout to a file, replacing its previous contents; >> appends. 2> writes stderr to a file. For example, python train.py >train.log 2>train.err keeps progress and errors separate.
Small tools become useful when composed. Make a tiny log, then count repeated error lines:
printf 'ERROR timeout\nERROR timeout\nINFO ok\nERROR quota\nERROR timeout\n' > app.log
grep 'ERROR' app.log | sort | uniq -c | sort -rn | head
grep keeps four error lines. The first sort puts identical lines together, which uniq -c requires to count all copies. uniq -c yields 3 ERROR timeout and 1 ERROR quota. sort -rn sorts counts numerically in descending order; head keeps the first ten results by default. If real log lines contain unique timestamps, extract the field you want to count first; counting whole lines would answer a different question. awk splits each line on whitespace into $1, $2, and so on.
printf '200 GET /a 12\n500 POST /b 90\n' | awk '{print $1}' # 200, then 500
printf '200 GET /a 12\n500 POST /b 90\n' | awk '{print $4, $3}' # 12 /a, then 90 /b
Printing $1 keeps the first field; print $4, $3 reorders fields. awk '$1 == 500' keeps only lines whose first field equals 500.
Commands also return an exit code: zero means success; nonzero means failure. Right after a command, $? contains its code. && runs the next command only after success; || runs it only after failure. Read chains carefully: each command changes $?.
grep -q 'ERROR' app.log
echo "$?" # 0: a match was found
test -f app.log && echo 'log exists'
test -f missing.log || echo 'log missing'
grep also returns nonzero when nothing matches. That answers "is the pattern present?"; it is not necessarily a broken program.
Processes and long jobs¶
A process is a running program. A foreground command occupies your terminal until it finishes. Add & to start it in the background; jobs lists jobs owned by that shell, and fg brings one back. Ctrl-C sends an interrupt signal to a foreground process. ps lists processes; top shows changing CPU and memory use.
kill PID asks a process to terminate with SIGTERM, giving it a chance to clean up. kill -KILL PID sends SIGKILL, which stops it without that chance; use it only when normal termination fails. Check the PID with ps before sending either signal. Backgrounding with & alone does not guarantee that a job survives closing a terminal or losing an SSH connection.
Environment, permissions, and scripts¶
An environment variable is a name and value passed to a process. PATH is the list of directories the shell searches for commands. PATH lists the directories searched for external commands; echo "$PATH" shows it. Run type python to see how this shell resolves python (which can miss aliases and functions). Machines with different PATH values can run different Pythons for the same command. An active virtual environment normally puts its own bin directory first on PATH.
Unix permissions distinguish read (r), write (w), and execute (x) access for owner, group, and others. ls -l shows those bits. A script file needs execute permission to run as ./script.sh; chmod +x script.sh adds it. You can still run bash script.sh by explicitly invoking Bash when the file is readable.
#!/usr/bin/env bash
set -euo pipefail
log_file="${1:?pass a log path}"
grep 'ERROR' "$log_file" | sort | uniq -c
Save this as errors.sh, then run bash errors.sh app.log. The shebang selects Bash when you execute the file directly. Shell variables need quotes when used as paths so spaces stay within one argument. set -e exits on many unhandled failures, -u rejects unset variables, and pipefail makes a pipeline fail if an earlier stage fails. Because grep returns nonzero when there are no matches, this strict script also exits nonzero for a clean log; handle that case explicitly if a clean log should count as success.
Working on another machine¶
ssh host opens a shell on a remote machine. scp local.csv host:project/ copies a file there; rsync is useful when you need to synchronize a directory again after changes. For long interactive work, start tmux on the remote machine, launch the job inside it, then detach; the session can be reattached after a disconnect. nohup keeps a noninteractive job running after logout; redirect its output to a log.
For AI engineers¶
For AI engineers
A training or evaluation command may run for hours. Start it in tmux (or use nohup), write its output to a log, and use tail -f train.log to watch progress. Use top for CPU and memory; nvidia-smi is an example GPU check where available. Before loading a large dataset into pandas, sample it with head, count lines with wc -l, filter with grep, select fields with cut, and count repeated values with sort | uniq -c. When checkpoints fail because storage is full, df -h shows free space on filesystems and du -sh checkpoints/ shows that directory's size.
Common mistakes¶
- Running
rm -rf "$target/checkpoints"before checking thattargetis set to the intended directory. If it is empty, the path becomes/checkpointsand could delete the wrong tree. - Leaving a path with spaces unquoted, so the shell passes multiple arguments instead of one.
- Using
sudo pip install, which can modify the system Python; activate a project virtual environment and install there. - Running a long training job in a plain SSH session and losing it when the connection closes.
- Forgetting that
>overwrites a log or result file; use>>only when appending is intentional. - Parsing the formatted output of
lsin a script; use path globs orfindto select files.
Check yourself¶
From project/, what do ./data and ../project/data refer to?
They both refer to the data directory inside project. The first starts here; the second goes to the parent and back into project.
A command writes results through > and suddenly the old file contents are gone. What happened, and how would you append next time?
> replaced the file's contents with stdout. Use >> to append stdout, after checking that appending is what you want.
Why does uniq -c need sort before it when counting all occurrences of an error line?
uniq -c counts adjacent identical lines. sort groups identical lines so each line gets one total count.
Your remote training job stopped when your laptop disconnected. What should you change for the next run?
Run it inside a remote tmux session, or use nohup with a log. A background & alone does not ensure survival after the shell exits.
Lab¶
In code/terminal-unix/, fill in five shell one-liners in starter/lab.py. The tests create a small access log and run each command from a temporary directory. Count errors, rank IPs, summarize status codes, and find the five slowest requests. Finish with a command whose exit code detects any 5xx response. Run: cd code/terminal-unix && PYTHONPATH=starter python -m pytest tests -q Done means your commands return the requested output and the exit check works with and without 5xx lines.
Go deeper¶
- MIT Missing Semester for the shell, command-line environment, and remote work.
- Python documentation for virtual environments and running Python from the command line.
- Software Engineering Handbook, ch. 2 "OS & Concurrency" for processes and operating-system concepts.