Shell Words Tokenizer

Split a command line into arguments with single quotes, double quotes, escapes, and explicit errors for unterminated quotes.

RustSecurity Boundaries

Code

rustsnippet
66 lines
#[derive(Clone, Copy, PartialEq)]
enum Quote {
    None,
    Single,
    Double,
}

fn split_shell_words(input: &str) -> Result<Vec<String>, String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut started = false;
    let mut quote = Quote::None;
    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        match (quote, ch) {
            (Quote::None, '\'') => {
                quote = Quote::Single;
                started = true;
            }
            (Quote::None, '"') => {
                quote = Quote::Double;
                started = true;
            }
            (Quote::None, '\\') => match chars.next() {
                Some(escaped) => {
                    current.push(escaped);
                    started = true;
                }
                None => return Err("trailing backslash".to_string()),
            },
            (Quote::None, whitespace) if whitespace.is_whitespace() => {
                if started {
                    words.push(std::mem::take(&mut current));
                    started = false;
                }
            }
            (Quote::Single, '\'') => quote = Quote::None,
            (Quote::Double, '"') => quote = Quote::None,
            (Quote::Double, '\\') => match chars.next() {
                Some(escaped) => current.push(escaped),
                None => return Err("trailing backslash".to_string()),
            },
            (_, character) => {
                current.push(character);
                started = true;
            }
        }
    }

    if quote != Quote::None {
        return Err("unterminated quote".to_string());
    }
    if started {
        words.push(current);
    }
    Ok(words)
}

fn main() {
    let command = r#"git commit -m "fix: handle \"quoted\" text" --no-verify"#;
    println!("{:?}", split_shell_words(command));
    println!("{:?}", split_shell_words("echo 'literal value'"));
    println!("{:?}", split_shell_words("run \"a b\" c"));
    println!("error: {:?}", split_shell_words("echo 'unterminated"));
}

What the code does

Shell Words Tokenizer keeps everything in the functions split_shell_words and main.

Iteration happens inside while let Some(ch) = chars.next() — everything outside it runs once. Result turns the error into data — visible in the type, handled by the caller. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.

What to watch for

  • The Result values will not let errors pass silently; each must be matched, unwrapped, or propagated.

Using it

The main signature reads fn split_shell_words(input: &str) -> Result<Vec<String>, String>

Output lines are prefixed (error:), making each step’s effect easy to spot.

The demo flow inside main is split_shell_words — run the file to see it end to end.

Key statements

(Quote::None, '\\') => match chars.next() {
Some(escaped) => {
current.push(escaped);
started = true;
}
None => return Err("trailing backslash".to_string()),
},
(Quote::None, whitespace) if whitespace.is_whitespace() => {
if started {
words.push(std::mem::take(&mut current));
started = false;
}
}
(Quote::Double, '\\') => match chars.next() {
Some(escaped) => current.push(escaped),
None => return Err("trailing backslash".to_string()),
},

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Shell Words Tokenizer print when run?
Invoke the file as-is — the `error:` prefixes identify which step printed each line.