knaxuslearn · build · ship

Projects / Unix shell

Rust · about 10 hours · 4 phases

Build a Unix shell in Rust

You type ls | sort > out.txt hundreds of times a week. What does the shell actually do with that line? Who creates the pipe, who starts the two programs, and why does Ctrl-C stop sleep but leave the shell alone? The best way to find out is to write one. In about 10 hours you will build a small shell in Rust, one layer at a time, and every layer ends with something you can run.

You work in four phases of about 2.5 hours each. By the end you will have a shell that:

  • reads a line, understands quotes and escapes, and runs programs and built-ins,
  • connects programs with pipes and sends their input and output to files,
  • keeps variables, expands $NAME and $?, and chains commands with ;, && and ||,
  • runs jobs in the background, and pauses, resumes and interrupts them with Ctrl-Z, fg, bg and Ctrl-C.

You need basic Rust (ownership, Result, match, Vec, and String) and a terminal. Processes, pipes and signals are explained when they first show up.

If ownership or Result still feels shaky, read chapters 4 and 9 of The Rust Programming Language first. This project makes much more sense once those two ideas are familiar.

The four phases

  1. Read, split, run

    You end with a shell that runs programs, understands quotes, and has cd, pwd and exit.

    • 1.1 The read-eval loop30 min
    • 1.2 Splitting a line into words45 min
    • 1.3 Built-ins, and why cd cannot be a program35 min
    • 1.4 Run a program, and report how it ended40 min
  2. Pipes and redirects

    You end with a shell that runs a | b | c, sends output to files and reads input from them, and does it by calling fork, pipe, dup2 and exec yourself.

    • 2.1 From words to a structure35 min
    • 2.2 fork and exec by hand40 min
    • 2.3 Pipes45 min
    • 2.4 Redirects30 min
  3. Variables and lists

    You end with a shell that expands $NAME, $? and ~, supports export, chains commands with ;, && and ||, and runs script files.

    • 3.1 Expand late, not early40 min
    • 3.2 Variables, export and $?40 min
    • 3.3 Lists with ;, && and ||40 min
    • 3.4 Scripts and -c30 min
  4. Job control

    You end with a shell where sleep 100 & runs in the background, Ctrl-Z pauses a program, fg and bg bring it back, and Ctrl-C stops only the program, never the shell.

    • 4.1 Why Ctrl-C does not kill the shell30 min
    • 4.2 Give each job a group, and the terminal45 min
    • 4.3 Background jobs and reaping40 min
    • 4.4 Stop, fg and bg35 min

Start with the setup →