0-Shell is a Unix-like shell implementation written in Rust. It provides an interactive command-line interface with support for basic shell features including command execution, history, environment variables, and various built-in commands.
0-shell/
├── Cargo.toml # Rust project configuration and dependencies
├── Dockerfile # Container configuration for development/testing
├── Makefile # Build and run commands
├── README.md # Project documentation
└── src/ # Source code directory
- colored: Terminal color output
- dirs: Cross-platform directory utilities
- fs: File system operations
- lazy_static: Static initialization
- regex: Regular expressions
- chrono: Date/time handling
- users: User/group information
- termion: Terminal input/output handling
- whoami: Username utilities
src/main.rs: Application entry point, initializes and runs the shellsrc/lib.rs: Library root, exports public modules and utilities
- Shell struct: Main shell state management
- Terminal I/O handling (stdin/stdout)
- Command buffer management
- Cursor position tracking
- History integration
- Environment state
Key Features:
- Raw terminal mode support
- Interactive command editing
- History navigation (Up/Down arrows)
- Cursor movement (Left/Right arrows)
- Terminal clearing (Ctrl+L)
- Signal handling (Ctrl+C, Ctrl+D, Ctrl+Z)
-
types.rs: Token and word definitionsToken: Lexical tokens (Word, Pipe, Redirect, etc.)Word: Shell words with parts and quotingWordPart: Word components (Literal, VariableSubstitution, etc.)QuoteType: Quoting types (Single, Double, None)State: Lexer state machine states
-
tokenize.rs: Tokenizer implementation- Character-by-character parsing
- Variable substitution recognition (
$VAR,${VAR}) - Arithmetic substitution (
$((expr))) - Command substitution (
$(cmd)) - Quote handling
- Redirection operators
types.rs: Abstract Syntax Tree (AST) definitionsAstNode: All shell constructs (Command, Pipeline, If, While, etc.)ArithmeticExpr: Mathematical expressionsRedirect: I/O redirection specificationsBinaryOperator/UnaryOperator: Arithmetic operators
Parser Modules:
parse_command.rs: Command parsing with assignments and redirectionsparse_pipeline.rs: Pipeline operator (|) parsingparse_sequence.rs: Command sequences (;)parse_if.rs: Conditional statementsparse_while.rs: Loop constructsparse_for.rs: For loopsparse_function.rs: Function definitionsparse_group.rs: Command grouping{...}parse_redirection.rs: I/O redirection parsingparse_assignment.rs: Variable assignments
-
execute(): Main execution function- AST traversal and interpretation
- Built-in command dispatch
- External command execution
- Environment variable expansion
- Error handling and exit codes
-
build_command(): Command factory- Maps command names to implementations
- Supports: echo, cd, ls, pwd, cat, cp, rm, mv, mkdir, export, exit
- ShellEnv struct: Complete shell environment
- Shell variables (
HashMap<String, String>) - Arithmetic variables (
HashMap<String, i64>) - User-defined functions (
HashMap<String, AstNode>) - Job control (
HashMap<usize, Job>) - Exit status tracking
- Shell start time
- Shell variables (
Key Methods:
set_var()/get_var(): Variable managementset_arith()/get_arith(): Arithmetic variablesadd_job()/get_job(): Job controlset_last_status()/get_last_status(): Exit status
Each command implements the ShellCommand trait:
echo.rs: Print text with quote handlingcd.rs: Change directoryls.rs: List directory contents with formatting optionspwd.rs: Print working directorycat.rs: Concatenate and display filescp.rs: Copy files and directoriesrm.rs: Remove files and directoriesmv.rs: Move/rename filesmkdir.rs: Create directoriesexport.rs: Set environment variables
History System (src/features/history.rs)
- Persistent command history storage
- Navigation through history (Up/Down arrows)
- Automatic history saving
- File-based persistence (
~/.0-shell_history)
Job Control (src/jobs.rs)
- Background job management
- Job status tracking (Running, Stopped, Done)
- Process group management
- Job ID assignment
Error Handling (src/error.rs)
ShellErrorenum with comprehensive error types- IO, syntax, parsing, evaluation, execution errors
- Error conversion traits
Configuration (src/config.rs)
- Environment variable initialization
- User information setup
- Shell configuration defaults
Expansion (src/expansion.rs)
- Variable expansion (
$VAR) - Default value expansion (
${VAR:-default}) - Arithmetic expansion (
$((expr)))
Evaluation (src/eval.rs)
- Arithmetic expression evaluation
- Mathematical operations
- Variable substitution in expressions
- Input: User types command in interactive shell
- Lexical Analysis:
Tokenizerconverts input to tokens - Parsing:
Parserbuilds AST from tokens - Expansion: Variables and expressions are expanded
- Execution:
execute()interprets AST and runs commands - Output: Results displayed, history updated
- File operations: ls, cat, cp, rm, mv, mkdir
- Navigation: cd, pwd
- Output: echo
- Environment: export
- Utilities: type, test, true, false
- Job control: jobs, fg, bg, kill
- Control: exit
- Command sequences (
;) - Fully working - Pipelines (
|) - Multi-stage pipelines supported - Logical operators (
&&,||,!) - All working - Background execution (
&) - Supported - Variable assignments - Working
- I/O redirection (
>,>>,<) - Working when directories exist - Command grouping (
{ }) - Fully functional
- Conditionals:
if-then-elif-else-fi- All branches working - Loops:
for-in-do-done- Fully working - Loops:
while-do-done- Working (arithmetic in conditions has limitations) - Loops:
until-do-done- Working (arithmetic in conditions has limitations) - Loop control:
break,continue- With optional levels, fully working - Functions:
name() { body; }- Fully implemented with argument support
- Function definitions and calls
- Function arguments (
$1,$2, etc.) - Nested function calls
- Function redefinition
- Positional parameter scoping
- Functions with control structures
- Functions with pipelines and redirections
- Command history with persistent storage
- Line editing (insert, delete, cursor movement)
- History navigation (Up/Down arrows)
- Terminal control (Ctrl+C, Ctrl+D, Ctrl+Z, Ctrl+L)
- Dynamic prompt
- Subshells:
(cmd1; cmd2)- Parse error, not yet implemented - Arithmetic in test conditions:
$((i+1))in while/until loops has issues - File operation flags:
mkdir -pandrm -rfdon't support flags - Pipelines with control structures: Pipelines can only contain commands
- Redirection to non-existent directories: Requires parent directory to exist first
- Subshells:
(cmd1; cmd2)- Parse error needs fixing - Arithmetic expressions: Full support for
$((expr))in all contexts - Command substitution:
$(command)- Not yet implemented - Advanced expansion:
${VAR:-default},${VAR:+value}, etc. - Case statements:
case-esacconstruct - Here documents:
<<heredoc support - File operation flags: Proper support for
-p,-rf, etc.
cargo build
cargo runmake build
make runcargo testShellCommandtrait for command implementations- Consistent interface across all built-ins
- Lexer uses state machine for token recognition
- Parser maintains position and lookahead
ShellEnvpassed through execution chain- Mutable environment updates
Result<T, ShellError>throughout codebase- Comprehensive error handling
- Pattern matching extensively
- Error handling with
Result - Generic types and traits
- Memory safety without garbage collection
- Zero-cost abstractions
- Efficient string handling
- Minimal allocations
- Direct terminal I/O
- Lazy evaluation where appropriate
- Complete control structure implementation
- Advanced job control
- Signal handling
- Subshell support
- Function definitions
- Arithmetic expressions
- Advanced expansion features
- Better error messages
- More comprehensive testing
- Performance optimizations
- Additional built-in commands
- Plugin system
- Configuration file support