knaxuslearn · build · ship

Projects / Unix shell / Phase 1

Phase 1 of 4 · about 2.5 hours

Read, split, run

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

A shell is a program with one job: read a line from you, work out what you asked for, and start other programs to do it. Starting a program means asking the operating system to create a new process, which is a running copy of a program with its own memory and its own list of open files. The first version uses Rust's standard library to do that, and we take the controls ourselves in Phase 2.

Step 1.1: The read-eval loop (about 30 minutes)

Every shell has the same heart: print a prompt, read a line, run it, repeat. Make d1/src/main.rs with this loop:

fn main() {
    let interactive = io::stdin().is_terminal();
    let stdin = io::stdin();
    let mut status = 0;

    loop {
        if interactive {
            print!("rsh$ ");
            io::stdout().flush().ok();
        }
        let mut line = String::new();
        match stdin.lock().read_line(&mut line) {
            Ok(0) => break, // end of input (Ctrl-D)
            Ok(_) => {}
            Err(e) => {
                eprintln!("rsh: {e}");
                break;
            }
        }
        let argv = match lexer::split_words(&line) {
            Ok(words) => words,
            Err(msg) => {
                eprintln!("rsh: {msg}");
                status = 2;
                continue;
            }
        };
        if argv.is_empty() {
            continue;
        }
        status = run_builtin(&argv).unwrap_or_else(|| run_external(&argv));
    }
    std::process::exit(status);
}

Walk through it:

  • The prompt appears only when a person is typing. is_terminal is false when the input comes from a file or a pipe, so scripted runs stay clean.
  • read_line returns Ok(0) at the end of the input. At a terminal that is what Ctrl-D sends, and it is how you leave the shell without typing exit.
  • The variable status holds the exit status of the last command. By convention 0 means success and anything else means failure. The shell hands it to its own caller when it ends, which is the exit(status) at the bottom.
  • Syntax errors set the status to 2 and the loop carries on. A typo must never end your session.

Step 1.2: Splitting a line into words (about 45 minutes)

You might think a line is split on spaces. Try echo "two spaces": the quotes must keep the two spaces together and then disappear. So we write a small scanner that reads one character at a time and remembers where it is: inside single quotes, inside double quotes, or outside both.

/// Split one line into words. Quotes group characters, a backslash escapes the next one.
pub fn split_words(line: &str) -> Result<Vec<String>, String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut in_word = false; // true once the current word has started, even if it is empty ("")
    let mut chars = line.chars();

    while let Some(c) = chars.next() {
        match c {
            ' ' | '\t' | '\n' => {
                if in_word {
                    words.push(std::mem::take(&mut current));
                    in_word = false;
                }
            }
            '\'' => {
                in_word = true;
                loop {
                    match chars.next() {
                        Some('\'') => break,
                        Some(ch) => current.push(ch),
                        None => return Err("unterminated single quote".into()),
                    }
                }
            }
            '"' => {
                in_word = true;
                loop {
                    match chars.next() {
                        Some('"') => break,
                        Some('\\') => match chars.next() {
                            Some(ch @ ('"' | '\\')) => current.push(ch),
                            Some(ch) => {
                                current.push('\\');
                                current.push(ch);
                            }
                            None => return Err("unterminated double quote".into()),
                        },
                        Some(ch) => current.push(ch),
                        None => return Err("unterminated double quote".into()),
                    }
                }
            }
            '\\' => {
                in_word = true;
                match chars.next() {
                    Some(ch) => current.push(ch),
                    None => return Err("line ends with a backslash".into()),
                }
            }
            _ => {
                in_word = true;
                current.push(c);
            }
        }
    }
    if in_word {
        words.push(current);
    }
    Ok(words)
}

The rules, as the code writes them:

  • Outside quotes, spaces end a word. Everything else joins it.
  • Single quotes keep every character exactly as typed, up to the closing quote.
  • Double quotes do the same, except that a backslash before " or \ escapes it. (In Phase 3 $ will join that list.)
  • A backslash outside quotes escapes the next character, so a\ b is one word.
  • in_word is separate from current because "" is a real, empty word: printf '[%s]\n' "" prints [], and without the flag the empty word would vanish.
  • A quote that never closes is an error, not a silent guess.

The file ends with unit tests for each rule. Run them:

running 6 tests
......
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

A scanner like this is called a lexer: it turns characters into tokens. Real shells have the same layer, and we will extend ours in Phase 2.

Step 1.3: Built-ins, and why cd cannot be a program (about 35 minutes)

Try to imagine cd as a separate program. The shell would start it, it would change its own working directory, and then it would exit. The shell's directory would not change at all, because every process has its own. So some commands must run inside the shell itself. These are built-ins.

/// Run a built-in if `argv[0]` names one. Returns the exit status, or None when it is not a built-in.
fn run_builtin(argv: &[String]) -> Option<i32> {
    match argv[0].as_str() {
        "exit" => {
            let code = argv.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
            std::process::exit(code);
        }
        "pwd" => {
            match env::current_dir() {
                Ok(dir) => println!("{}", dir.display()),
                Err(e) => {
                    eprintln!("pwd: {e}");
                    return Some(1);
                }
            }
            Some(0)
        }
        "cd" => {
            let target = match argv.get(1) {
                Some(dir) => dir.clone(),
                None => env::var("HOME").unwrap_or_else(|_| "/".into()),
            };
            match env::set_current_dir(&target) {
                Ok(()) => Some(0),
                Err(e) => {
                    eprintln!("cd: {target}: {e}");
                    Some(1)
                }
            }
        }
        _ => None,
    }
}
  • exit ends the shell with an optional status.
  • pwd prints the current directory.
  • cd with no argument goes to $HOME, and a failure prints the reason and returns status 1.
  • The function returns None for anything that is not a built-in. The loop then falls back to starting a program.

Step 1.4: Run a program, and report how it ended (about 40 minutes)

For everything else we ask the standard library to start the program, wait for it, and tell us how it ended:

fn run_external(argv: &[String]) -> i32 {
    match Command::new(&argv[0]).args(&argv[1..]).status() {
        Ok(status) => status.code().unwrap_or(128),
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            eprintln!("rsh: {}: command not found", argv[0]);
            127
        }
        Err(e) => {
            eprintln!("rsh: {}: {e}", argv[0]);
            126
        }
    }
}

Three outcomes matter, and shells have agreed on numbers for them:

StatusMeaning
the program's own codeit ran and chose its status
127the command was not found
126it was found but could not be run (no permission, say)

status.code() is None when a signal killed the program, because then there was no exit code at all. We report 128, and Phase 2 will add the usual rule of 128 plus the signal number.

Build it and run a short script through it:

cd d1
cargo build --release
echo hello world
echo "two  spaces" 'and $HOME stays'
cd /usr
pwd
ls /nonexistent
nosuchcmd
echo "unterminated
hello world
two  spaces and $HOME stays
/usr
ls: cannot access '/nonexistent': No such file or directory
rsh: nosuchcmd: command not found
rsh: unterminated double quote
exit status: 2

The unterminated quote on the last line was refused with a message, the shell kept going, and the final status is the 2 that a syntax error sets.

Phase 1 done

You have about 185 lines of Rust, tests included, and a shell that you can use for simple work. It has no pipes, no redirects and no variables, and all three need a better idea of what a command line is. That is what Phase 2 builds.