Rash - Bidirectional Shell Safety Tool
Rash is a bidirectional shell safety tool that lets you write shell scripts in REAL Rust and automatically purify legacy bash scripts.
Why Rash?
- ๐ก๏ธ Safety First: Automatic protection against shell injection attacks
- ๐ Compile-Time Verification: Catch errors before deployment
- ๐ฆ Zero Runtime Dependencies: Generated scripts work on any POSIX shell
- ๐ฏ Deterministic Output: Same input always produces identical scripts
- โ ShellCheck Compliant: All output passes strict linting
How Rash Exceeds ShellCheck
ShellCheck is an excellent linter that detects problems in shell scripts. Rash goes far beyond by understanding the full AST and automatically transforming code to fix issues.
| What ShellCheck Does | What Rash Does |
|---|---|
| โ ๏ธ Warns: "$RANDOM is non-deterministic" | โ Rewrites to version-based deterministic IDs |
| โ ๏ธ Warns: "mkdir may fail if exists" | โ
Transforms to mkdir -p (idempotent) |
| โ ๏ธ Warns: "Unquoted variable expansion" | โ Quotes all variables automatically |
| โ ๏ธ Warns: "Timestamp in $(date +%s)" | โ Replaces with fixed version tags |
| โ ๏ธ Warns: "rm may fail if doesn't exist" | โ
Adds -f flag for safe removal |
| Static pattern matching | Full AST semantic understanding |
| Detects issues (read-only) | Fixes issues (read-write transformation) |
Example: Non-Deterministic Deployment Script
Input (Messy Bash):
#!/bin/bash
SESSION_ID= # Non-deterministic
RELEASE="release-" # Timestamp-based
ShellCheck Output (manual fixes required):
โ ๏ธ SC2086: Quote variable to prevent word splitting
โ ๏ธ $RANDOM is non-deterministic (YOU must fix manually)
โ ๏ธ mkdir may fail if directory exists (YOU must add -p flag)
โ ๏ธ rm may fail if doesn't exist (YOU must add -f flag)
Rash Output (automatically purified):
#!/bin/sh
# โ
Automatically fixed by Rash - no manual work needed
Key Difference: ShellCheck tells you what's wrong. Rash understands your code's intent and rewrites it to be safe, deterministic, and idempotent โ automatically.
This is only possible because Rash parses shell scripts into a full Abstract Syntax Tree (AST), understands the semantic meaning of each construct, and can perform intelligent transformations that preserve functionality while eliminating entire classes of bugs.
How Rash Works: Two Workflows
Rash operates in two directions to maximize shell script safety:
๐ PRIMARY: Rust โ Safe Shell (Production-Ready)
Write new scripts in REAL Rust, transpile to provably safe shell.
Rust Code (.rs) โ cargo test โ Transpile โ Safe POSIX Shell
โ Test FIRST with Rust tooling
Use cases:
- Bootstrap installers (Node.js, Rust toolchain, etc.)
- CI/CD deployment scripts
- System configuration tools
- Any new shell automation
Benefits:
- Full Rust std library support
- Test with
cargo test, lint withcargo clippy - Property-based testing with proptest
- 100% deterministic, idempotent output
๐ SECONDARY: Bash โ Rust โ Purified Bash (Legacy Cleanup)
Ingest messy bash, convert to Rust with tests, output purified shell.
Messy Bash โ Parser โ Rust + Tests โ Transpile โ Purified Bash
โ Tests auto-generated
Use cases:
- Clean up legacy bash scripts
- Remove non-deterministic constructs ($RANDOM, timestamps, $$)
- Enforce idempotency (mkdir -p, rm -f)
- Generate comprehensive test suites
Benefits:
- Automatic test generation
- Remove unsafe patterns
- Maintain shell compatibility
- Preserve functionality while improving safety
See examples/PURIFICATION_WORKFLOW.md for detailed purification examples.
Quick Start (PRIMARY Workflow)
Write Rust:
// install.rs
Get POSIX shell:
#!/bin/sh
# Generated by Rash v0.4.0
# POSIX-compliant shell script
IFS='
'
# Rash runtime functions
# Main script begins
# Execute main function
Installation
From crates.io (Recommended)
# Install latest release candidate
# Or install latest stable
Binary Releases
Pre-built binaries are available for Linux and macOS:
# Linux x86_64
|
# macOS x86_64
|
# macOS ARM64
|
Using cargo-binstall
From Source
# Full build with all features
# Minimal build (smaller binary, ~2MB)
Usage
Basic Commands
# Transpile a Rust file to shell
# Check if a file is valid Rash
# Initialize a new Rash project
# Verify safety properties
# Inspect AST and safety properties
# Lint shell scripts for safety issues (NEW in v1.1)
# Compile to self-extracting script (BETA)
Native Linter (NEW in v1.1) ๐
bashrs includes a native linter that validates shell scripts for safety issues, with zero external dependencies:
# Lint a shell script (human-readable output)
;
)))
# JSON format for CI/CD integration
{
{
}
}
# SARIF format for security scanners
Linter Features:
- โ Zero external dependencies - No ShellCheck installation required
- โ 3 output formats - Human, JSON, SARIF for CI/CD integration
- โ
Auto-fix (NEW in v1.2) - Automatically apply fixes with
--fixflag - โ Smart detection - Context-aware to prevent false positives
- โ ShellCheck parity - Implements critical SC-series rules
Auto-Fix (NEW in v1.2):
# Apply fixes automatically (creates backup)
)
Before:
DIR=/tmp/mydir
FILES=
After:
DIR=/tmp/mydir
FILES=""
Rules Implemented (v1.1):
- SC2086: Unquoted variable expansion (prevents word splitting & glob expansion)
- SC2046: Unquoted command substitution
- SC2116: Useless echo in command substitution
Exit Codes:
0- No issues found1- Warnings detected2- Errors detected
Comparison: bashrs vs ShellCheck:
| Feature | ShellCheck | bashrs |
|---|---|---|
| Core Capability | Static pattern detection | Full AST parsing + transformation |
| Output | Warnings only | Automatically fixed code |
| Installation | External binary required | Built-in, zero dependencies |
| Output formats | checkstyle, gcc, json | human, JSON, SARIF |
| Auto-fix | โ No | โ Yes - automatic code transformation |
| Determinism | Warns about $RANDOM | Replaces with deterministic constructs |
| Idempotency | Warns about mkdir | Transforms to mkdir -p |
| Semantic understanding | Pattern matching only | Full AST semantic analysis |
| Code transformation | โ Read-only | โ Read-write (purification) |
| Performance | ~50ms | <2ms (native Rust) |
See the Safety Comparison Guide for detailed vulnerability prevention examples.
CLI Options
)
)
)
)
Documentation
๐ The Rash Book
Comprehensive guide with tested examples: https://paiml.github.io/bashrs/
The Rash Book is the official, comprehensive documentation for Rash. All code examples in the book are automatically tested, ensuring they stay up-to-date with the code.
What's in the book:
- Getting Started: Installation, quick start, your first purification
- Core Concepts: Determinism, idempotency, POSIX compliance
- Shell Script Linting: Security, determinism, and idempotency rules
- Configuration Management: Purifying .bashrc and .zshrc files (CONFIG-001, CONFIG-002)
- Makefile Linting: Security and best practices
- Real-World Examples: Bootstrap installers, deployment scripts, CI/CD
- Advanced Topics: AST transformation, property testing, mutation testing
- Reference: CLI commands, configuration, exit codes, rules reference
Why the book is special:
- โ All examples are tested automatically (TDD)
- โ Cannot release without updating the book
- โ Enforced quality through pre-release checks
- โ Toyota Way principles applied to documentation
API Documentation
Rust API documentation is available on docs.rs/bashrs.
Quick Links
- Installation Guide
- Quick Start
- CONFIG-001: PATH Deduplication
- CONFIG-002: Quote Variables
- Security Rules
- Contributing Guide
Language Features
Supported Rust Subset
Rash supports a carefully chosen subset of Rust that maps cleanly to shell:
Variables and Types
let name = "Alice"; // String literals
let count = 42; // Integers (including negatives: -42)
let flag = true; // Booleans
let user = env; // Environment variables
let result = capture; // Command output
Arithmetic Operations
let x = 1 + 2; // Addition โ $((1 + 2))
let y = 10 - 3; // Subtraction โ $((10 - 3))
let z = 4 * 5; // Multiplication โ $((4 * 5))
let w = 20 / 4; // Division โ $((20 / 4))
Comparison Operators
if x > 0
if y == 5 // Equal โ [ "$y" -eq 5 ]
if z < 10 // Less than โ [ "$z" -lt 10 ]
User-Defined Functions
Built-in Functions
// I/O operations
echo; // Print to stdout
println!; // println! macro (Sprint 10)
eprint; // Print to stderr
// File system
mkdir_p; // Create directory recursively
write_file; // Write file
let content = read_file; // Read file
if path_exists // Check path
// Process management
exec; // Run command
let output = capture; // Capture command output
exit; // Exit with code
// Environment
set_env; // Set environment variable
let val = env; // Get environment variable
let val = env_var_or; // With default
Control Flow
// Conditionals
if condition else if other else
// โ
Pattern matching - SUPPORTED (experimental in v1.0.0-rc1)
match value
Loops โ (Supported in v1.0.0-rc1)
// โ
For loops - FULLY SUPPORTED
for i in 0..10
// โ
While loops - FULLY SUPPORTED
let mut count = 0;
while count < 10
Safety Features
All generated scripts are protected against:
- Command Injection: All variables are properly quoted
- Path Traversal: Paths are validated and escaped
- Glob Expansion: Glob patterns are quoted when needed
- Word Splitting: IFS is set to safe value
- Undefined Variables:
set -ucatches undefined vars
Example of automatic safety:
let user_input = env;
exec; // Safe: becomes echo "$user_input"
Beta Features โ๏ธ
The following features are available but marked as experimental in v1.0:
Binary Compilation (BETA)
Compile Rust to self-extracting shell scripts or container images:
# Self-extracting script (includes runtime)
# Container image (OCI format)
Status:
- โ Self-extracting scripts work and are tested
- โ ๏ธ Container packaging is experimental
- โ ๏ธ Binary optimization is in progress
Limitations:
- Container formats are not fully implemented
- Advanced runtime optimizations pending
- Limited to dash/bash/busybox runtimes
Recommendation: Use bashrs build for production deployments. Use compile for quick testing or when you need a single-file installer.
Proof Generation (BETA)
Generate formal verification proofs alongside transpiled scripts:
This creates output.proof with formal correctness guarantees.
Status: โ ๏ธ Proof format is experimental and may change
Examples
See the examples/ directory for complete examples:
-
Basic
- Hello World - Simplest example
- Variables - Variable usage and escaping
- Functions - Built-in functions
- Standard Library - Stdlib functions demo
-
Control Flow
- Conditionals - If/else statements
- Loops - Bounded iteration
-
Safety
- Injection Prevention - Security examples
- String Escaping - Special character handling
-
Real-World
- Node Installer - Node.js bootstrap script
- Rust Installer - Rust toolchain installer
Shell Compatibility
Generated scripts are tested on:
| Shell | Version | Status |
|---|---|---|
| POSIX sh | - | โ Full support |
| dash | 0.5.11+ | โ Full support |
| bash | 3.2+ | โ Full support |
| ash (BusyBox) | 1.30+ | โ Full support |
| zsh | 5.0+ | โ Full support |
| mksh | R59+ | โ Full support |
Standards Compliance
bashrs adheres to industry-standard shell scripting best practices and specifications:
POSIX Shell Compliance
bashrs generates scripts compliant with the POSIX Shell Command Language specification:
| POSIX Feature | Implementation | Status |
|---|---|---|
| Variable quoting | Automatic single quotes for literals | โ Enforced |
| Command substitution | $(command) syntax |
โ Compliant |
| Arithmetic expansion | $((expression)) syntax |
โ Compliant |
| Parameter expansion | ${var} and "$var" patterns |
โ Compliant |
| Test expressions | [ condition ] POSIX syntax |
โ Compliant |
| String escaping | Proper handling of special characters | โ Safe |
Google Shell Style Guide
Aligns with Google's Shell Style Guide recommendations:
| Guideline | bashrs Approach | Status |
|---|---|---|
| Always quote variables | Automatic quoting (no unquoted vars possible) | โ Enforced |
Use $(...) not backticks |
Generates modern $(...) syntax |
โ Compliant |
| Check return values | Effect system tracks side effects | โ Implemented |
| Error messages to STDERR | Built-in eprint() function |
โ Available |
| Avoid complex shell scripts | Write Rust instead! | โ Core value |
ShellCheck Validation
All generated scripts pass ShellCheck static analysis:
- โ SC2086: No unquoted variable expansions (automatic quoting)
- โ SC2046: No unquoted command substitutions
- โ SC2116: No useless echo wrapping
- โ SC2005: No useless echo in command substitution
- โ 24/24 ShellCheck tests passing (100% compliance)
Safety Guarantees
bashrs provides automatic protection against common shell vulnerabilities:
| Vulnerability | Raw Shell Risk | bashrs Protection |
|---|---|---|
| Command Injection | Unquoted $var allows arbitrary commands |
All variables auto-quoted |
| Word Splitting | $var splits on IFS characters |
Uses "$var" or 'literal' |
| Glob Expansion | $var expands wildcards (*, ?) |
Proper quoting prevents expansion |
| Path Traversal | cd $dir allows ../../../etc |
Safe path handling |
| Exit on Error | Commands fail silently by default | set -e enforced (optional) |
Comparison: Raw Shell vs bashrs
Unsafe Raw Shell:
#!/bin/bash
USER_INPUT=
Safe bashrs:
Generated Safe Shell:
#!/bin/sh
IFS='
'
Standards Documentation
For detailed compliance information, see:
- POSIX Shell Specification
- Google Shell Style Guide
- ShellCheck Wiki
- bashrs Safety Comparison - Comprehensive vulnerability prevention guide
Performance
Rash is designed for fast transpilation with exceptional real-world performance:
Makefile Parsing & Purification (v3.0.0):
- Small Makefiles (46 lines): 0.034ms - 297x faster than 10ms target
- Medium Makefiles (174 lines): 0.156ms - 320x faster than 50ms target
- Large Makefiles (2,021 lines): 1.43ms - 70x faster than 100ms target
- Linear O(n) scaling: ~0.37 ยตs/line parsing, ~0.35 ยตs/line purification
Rust-to-Shell Transpilation:
- 21.1ยตs transpile time for simple scripts (100x better than target!)
- Memory usage <10MB for most scripts
- Generated scripts add minimal overhead (~20 lines boilerplate)
Quality Metrics (v3.0.0)
| Metric | Status | Notes |
|---|---|---|
| Tests | 1,752 passing โ | 100% pass rate (Sprints 81-84) |
| Property Tests | 52 properties โ | ~26,000+ test cases, 0 failures |
| Core Coverage | 94.85% โ | makefile/purify.rs (critical module) |
| Overall Coverage | 88.71% โ | All modules (exceeds 85% target) |
| Mutation Testing | 167 mutants identified โ | Comprehensive mutation analysis |
| Multi-Shell | 100% pass โ | sh, dash, bash, ash, zsh, mksh |
| ShellCheck | 100% pass โ | All generated scripts POSIX-compliant |
| Makefile Linter Rules | 28 transformations โ | Parallel, reproducibility, performance, error, portability |
| Makefile Parsing | 0.034-1.43ms โ | 70-320x faster than targets |
| Complexity | Median 1.0 โ | All core functions <10 |
| Edge Cases | 100% complete โ | All identified issues resolved |
v3.0.0 Status: โ PRODUCTION-READY - Phase 1 Complete: Makefile World-Class
Troubleshooting
Having issues? Check our Error Guide for common errors and solutions.
MCP Server
Rash provides a Model Context Protocol (MCP) server for AI-assisted shell script generation:
# Install from crates.io
# Run MCP server
The MCP server is available in the official registry as io.github.paiml/rash.
For developers: See MCP Registry Publishing Guide for details on the automated publishing process.
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
# Clone the repository
# Run tests
# Run with all checks
# Build release binary
Publishing to MCP Registry
For maintainers publishing new MCP server versions, see the MCP Registry Publishing Guide.
License
Rash is licensed under the MIT License. See LICENSE for details.
Acknowledgments
Rash is built with safety principles inspired by:
- ShellCheck for shell script analysis
- Oil Shell for shell language design
- The Rust community for memory safety practices
Roadmap
v3.0.0 (Current Release) โ
Status: PRODUCTION-READY - Phase 1 Complete: Makefile World-Class Released: 2025-10-20 Achievement: World-class Makefile linting, parsing, and purification with exceptional performance Quality Metrics:
- 1,752 tests passing (100% pass rate, Sprints 81-84)
- 94.85% coverage on critical modules (makefile/purify.rs)
- 88.71% overall coverage (exceeds 85% target)
- 167 mutants identified through comprehensive mutation testing
- 0 shellcheck warnings
- 52 property tests (~26,000+ cases)
- 70-320x faster than performance targets
Core Features (Complete):
- Makefile Purification (v3.0.0 - NEW!) - World-class linting and transformation
- 28 transformation types across 5 categories
- Parallel safety analysis, reproducibility enforcement
- Performance optimization, error handling detection
- Portability checks (bashisms, platform-specific commands)
- 70-320x faster than performance targets
- Rust-to-Shell transpilation (POSIX, Bash, Dash, Ash)
- Full AST parsing and validation (98.92% coverage)
- IR generation and optimization (87-99% coverage)
- Safety verification and escape handling (95.45% coverage)
- Multi-shell compatibility testing (100% pass rate)
- Property-based testing (114k executions, 0 failures)
- Fuzzing infrastructure (0 failures)
- ShellCheck compliance (24/24 tests pass)
- Arithmetic expressions and comparisons
- User-defined functions
-
println!macro support - MCP server (rash-mcp)
CLI Tools (Complete):
-
bashrs build- Transpile Rust to shell -
bashrs check- Validate Rust compatibility -
bashrs init- Project scaffolding -
bashrs verify- Script verification -
bashrs inspect- Formal verification reports
Shipped in v1.0.0-rc1:
- Control flow (if/else if/else) - STABLE
- For loops (0..n, 0..=n) - STABLE
- While loops (with max_iterations safety) - STABLE
- Match expressions (basic pattern matching) - EXPERIMENTAL
- Logical operators (&&, ||, !) - STABLE
- String and integer comparisons - STABLE
- Self-extracting scripts - STABLE
- Container packaging (in progress)
- Proof generation (experimental format)
v1.1.0 (Released - October 2025) โ
Native Linting (Complete):
-
bashrs lintsubcommand with zero external dependencies - SC2086 - Unquoted variable expansion detection
- SC2046 - Unquoted command substitution detection
- SC2116 - Useless echo detection
- Human, JSON, and SARIF output formats
- Auto-fix suggestions for all violations
- 48 comprehensive linter tests (100% passing)
- 88.5% code coverage (exceeds 85% target)
Quality Improvements:
- Increased test coverage from 85.36% to 88.5%
- Added 48 new linter tests (804 total tests)
- Comprehensive documentation with Sprint 1 report
v1.2 (Planned)
Enhanced Linting:
- SC2115 - Use
${var:?}to ensure variable is set - SC2128 - Expanding array without index
- BP-series rules (POSIX compliance validation)
- SE-series rules (Security taint analysis)
- Auto-fix application (
--fixflag) - AST-based semantic analysis (replace regex)
Interactive Features:
- Playground/REPL (separate
rash-playgroundcrate) - Web-based transpiler
- Live syntax highlighting
Language Features:
- For loops (
for i in 0..10) - SHIPPED in v1.0.0-rc1 - Match expressions (pattern matching) - SHIPPED in v1.0.0-rc1
- While loops - SHIPPED in v1.0.0-rc1
- Arrays and collections (advanced operations)
- Enhanced pattern matching guards
Tooling:
- Language server protocol (LSP)
- IDE integration examples
- Better error diagnostics
v1.2+ (Future)
Advanced Features:
- Incremental compilation
- More shell targets (fish, PowerShell, nushell)
- Package manager integration
- Advanced optimizations (constant folding, DCE)
- Formal verification with SMT solvers
Documentation:
- Video tutorials
- Interactive examples
- Best practices guide
See v1.0-feature-scope.md for detailed feature decisions.