knaxuslearn · build · ship

Projects / Unix shell / Phase 3

Phase 3 of 4 · about 2.5 hours

Variables and lists

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

Step 3.1: Expand late, not early (about 40 minutes)

Consider this line:

X=1; echo $X

If the shell expanded $X while it was reading the line, it would do so before the assignment ran, and print an empty line. Shells must expand each command just before they run it. So the lexer stops expanding and instead remembers how each piece of a word was written:

/// How a piece of a word was written. It decides which expansions apply.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Quote {
    None,   // bare text: $ and ~ expand
    Double, // "...": $ expands, ~ does not
    Single, // '...' or an escaped character: nothing expands
}

#[derive(Debug, Clone, PartialEq)]
pub struct Part {
    pub text: String,
    pub quote: Quote,
}

/// A word as typed, not yet expanded. `a"b c"$HOME` has three parts.
pub type Parts = Vec<Part>;

The word a"b c"'$d' becomes three parts, with three different rules. Bare text expands $ and ~. Double-quoted text expands $ but not ~. Single-quoted text, and any character after a backslash, expands nothing. The expansion itself is a short function that runs at execution time:

/// Replace `$NAME`, `${NAME}` and `$?` in `text`. Anything else after a `$` stays as typed.
fn expand_dollars(text: &str, shell: &Shell, out: &mut String) {
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != '$' {
            out.push(chars[i]);
            i += 1;
            continue;
        }
        match chars.get(i + 1) {
            Some('?') => {
                out.push_str(&shell.lookup("?"));
                i += 2;
            }
            Some('{') => match chars[i + 2..].iter().position(|&c| c == '}') {
                Some(len) => {
                    let name: String = chars[i + 2..i + 2 + len].iter().collect();
                    out.push_str(&shell.lookup(&name));
                    i += len + 3;
                }
                None => {
                    out.push('$');
                    i += 1;
                }
            },
            Some(&c) if c.is_ascii_alphabetic() || c == '_' => {
                let len = chars[i + 1..].iter().take_while(|c| c.is_ascii_alphanumeric() || **c == '_').count();
                let name: String = chars[i + 1..i + 1 + len].iter().collect();
                out.push_str(&shell.lookup(&name));
                i += len + 1;
            }
            _ => {
                out.push('$');
                i += 1;
            }
        }
    }
}
/// Expand one word. Returns None when an unquoted expansion came out empty: such a word disappears.
pub fn expand_word(parts: &[Part], shell: &Shell) -> Option<String> {
    let mut out = String::new();
    let mut any_quoted = false;
    for (index, part) in parts.iter().enumerate() {
        match part.quote {
            Quote::Single => {
                any_quoted = true;
                out.push_str(&part.text);
            }
            Quote::Double => {
                any_quoted = true;
                expand_dollars(&part.text, shell, &mut out);
            }
            Quote::None => {
                let mut text = part.text.as_str();
                // "~" and "~/..." at the very start of a word mean the home directory.
                let tilde = index == 0 && (text == "~" || text.starts_with("~/"));
                if tilde {
                    out.push_str(&shell.lookup("HOME"));
                    text = &text[1..];
                }
                expand_dollars(text, shell, &mut out);
            }
        }
    }
    if out.is_empty() && !any_quoted {
        None
    } else {
        Some(out)
    }
}

Three behaviours to notice:

  • $? is the status of the last command, and ${NAME} lets you write ${NAME}s so the name does not swallow the s.
  • ~ expands only at the very start of a bare word. a~ and "~" stay as typed.
  • An unquoted expansion that comes out empty makes the word disappear, so echo $UNSET x passes only x. A quoted one stays as an empty word, so echo "$UNSET" x passes two arguments.

The tests cover each of these:

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

One difference from real shells: bash and others split the result of an unquoted expansion into words and then expand wildcards in it. Ours never does. If TWO holds a b, then echo $TWO passes one argument, a b. That is simpler, and it dodges a famous source of shell bugs, but it also means that scripts written for bash may behave differently here.

Step 3.2: Variables, export and $? (about 40 minutes)

The shell keeps its variables in a map, next to the status of the last command:

use std::collections::HashMap;

/// Everything the shell remembers between commands.
pub struct Shell {
    pub vars: HashMap<String, String>, // shell variables; `export` also copies them into the environment
    pub status: i32,                   // exit status of the last command, for $?
}

impl Shell {
    pub fn new() -> Shell {
        Shell { vars: HashMap::new(), status: 0 }
    }

    /// The value of `$name`. Unset variables are empty, as in other shells.
    pub fn lookup(&self, name: &str) -> String {
        if name == "?" {
            return self.status.to_string();
        }
        match self.vars.get(name) {
            Some(value) => value.clone(),
            None => std::env::var(name).unwrap_or_default(),
        }
    }
}

A variable lookup checks the shell's own map first and then the environment. The environment is the list of NAME=value pairs that every process inherits from its parent when it starts, and the way that settings like PATH and HOME reach programs.

Plain NAME=value creates a shell variable, which only the shell sees. export is what puts it in the environment so that programs we start can read it:

/// `NAME=value` on its own is an assignment, not a command.
pub fn split_assignment(word: &str) -> Option<(&str, &str)> {
    let (name, value) = word.split_once('=')?;
    let mut chars = name.chars();
    let first = chars.next()?;
    if (first.is_ascii_alphabetic() || first == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
        Some((name, value))
    } else {
        None
    }
}
        "export" => {
            // `export NAME=value` sets and exports; `export NAME` exports what the shell already has.
            for arg in &argv[1..] {
                let (name, value) = match split_assignment(arg) {
                    Some((n, v)) => (n.to_string(), v.to_string()),
                    None => (arg.clone(), shell.lookup(arg)),
                };
                env::set_var(&name, &value);
                shell.vars.insert(name, value);
            }
            0
        }

A line that holds only NAME=value is recognised as an assignment before any program is looked up. The proof is in what a child process sees: run sh -c 'echo $GREETING' after export GREETING=hi, and again after a plain assignment.

Step 3.3: Lists with ;, && and || (about 40 minutes)

The parser now returns a list: pipelines, each with the separator that follows it.

/// What follows a pipeline in a list.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Sep {
    Always, // `;` or the end of the line: run the next one whatever happened
    And,    // `&&`: run the next one only if this one succeeded
    Or,     // `||`: run the next one only if this one failed
}

/// Pipelines joined by `;`, `&&` and `||`, with the separator that follows each.
pub type List = Vec<(Pipeline, Sep)>;

Running a list is a short loop. The rule for each pipeline depends on the separator before it and on the status of the last pipeline that actually ran:

/// Run a list: pipelines joined by `;`, `&&` and `||`. Returns the status of the last one that ran.
pub fn run_list(shell: &mut Shell, list: &List) -> i32 {
    let mut previous = Sep::Always;
    for (pipeline, sep) in list {
        let run = match previous {
            Sep::Always => true,
            Sep::And => shell.status == 0,
            Sep::Or => shell.status != 0,
        };
        if run {
            shell.status = run_pipeline(shell, pipeline);
        }
        previous = *sep;
    }
    shell.status
}
  • After ; the next pipeline always runs.
  • After && it runs only if the status is 0, so mkdir d && cd d never enters a directory that was not created.
  • After || it runs only if the status is not 0, which makes cmd || echo failed a one-line error handler.
  • A skipped pipeline leaves the status as it was. That is what makes false && echo no || echo fallback print only fallback. The && skips echo no and keeps the failure, and || then sees the failure and runs.

This is the usual left-to-right rule. It is the same rule real shells use for && and ||, which have equal priority.

Step 3.4: Scripts and -c (about 30 minutes)

A script is just the same loop reading from a file instead of the keyboard. The loop from Phase 1 becomes a function that accepts any source of lines, and main chooses one:

/// Read lines from `input` until it ends. The prompt only appears when a person is typing.
fn run_source(shell: &mut Shell, mut input: impl BufRead, prompt: bool) {
    loop {
        if prompt {
            print!("rsh$ ");
            io::stdout().flush().ok();
        }
        let mut line = String::new();
        match input.read_line(&mut line) {
            Ok(0) => break, // end of input (Ctrl-D)
            Ok(_) => run_line(shell, &line),
            Err(e) => {
                eprintln!("rsh: {e}");
                break;
            }
        }
    }
}
  • rsh script.sh reads the file.
  • rsh -c 'cmd' runs one string.
  • With no arguments it reads the keyboard and shows the prompt.
  • A # at the start of a word begins a comment (the lexer ends the line there), and exit 7 makes the shell's own status 7.

Here is a script that uses everything from this phase:

# variables and expansion
HOME=/srv/demo
NAME=world
echo "hello $NAME" 'and $NAME' and ~
X=1; echo x is $X
echo status $?
false
echo after false: $?
# lists
true && echo and-ran
false && echo and-skipped
false || echo or-ran
true || echo or-skipped
false && echo no || echo fallback
mkdir -p demo && cd demo && pwd | sed 's|.*/||'
cd ..
# export reaches children
export GREETING=hi
sh -c 'echo child sees $GREETING'
PLAIN=local
sh -c 'echo child sees [$PLAIN]'
echo "unset is [$NOPE] and $NOPE vanishes"
nosuchcmd || echo "not found gives $?"
ls /nonexistent 2>/dev/null; echo "ls gave $?"
echo 'a b' | wc -w
exit 7
hello world and $NAME and /srv/demo
x is 1
status 0
after false: 1
and-ran
or-ran
fallback
demo
child sees hi
child sees []
unset is [] and  vanishes
rsh: nosuchcmd: command not found
not found gives 127
ls gave 2
2
shell exit: 7

Compare it with the script, line by line. $? is 1 after false and 127 after the missing command. Only the exported variable reaches the child, and the plain one shows as an empty []. Lastly, exit 7 became the status that the shell handed back to us.

Phase 3 done

You have a small scripting language: variables, status codes, conditional chains, comments and script files, in about 860 lines of Rust all told, tests included. The remaining feature is the one that makes a shell feel alive at the keyboard.