Skip to content

Quick Start

Gordon T Watts edited this page Jan 26, 2026 · 2 revisions

Quick Start Guide

Get productive with MAINFRAME in 5 minutes.


Table of Contents


1. Install MAINFRAME

# Clone and configure
git clone https://github.com/gtwatts/mainframe.git ~/.mainframe
echo 'export MAINFRAME_ROOT="$HOME/.mainframe"' >> ~/.bashrc
echo 'source "$MAINFRAME_ROOT/lib/common.sh"' >> ~/.bashrc
source ~/.bashrc

# Verify
mainframe version

2. Your First Script

Create a file called hello.sh:

#!/bin/bash
source "$MAINFRAME_ROOT/lib/common.sh"

# String manipulation
name=$(trim_string "  World  ")
log_info "Hello, $name!"

# Create JSON (no jq required)
json_object "greeting=Hello" "name=$name" "timestamp=$(timestamp)"

Run it:

chmod +x hello.sh
./hello.sh

Output:

[INFO] Hello, World!
{"greeting":"Hello","name":"World","timestamp":"2024-01-15T10:30:00"}

3. Essential Functions

Logging

log_debug "Debugging info"     # Only shown if LOG_LEVEL=debug
log_info "Information"         # Standard output
log_warn "Warning message"     # Yellow warning
log_error "Error occurred"     # Red error

# With context
log_info "Processing file" "filename=data.csv" "size=1024"

UUIDs and Timestamps

uuid                    # 550e8400-e29b-41d4-a716-446655440000
timestamp               # 2024-01-15T10:30:00
now                     # 1705312200 (Unix timestamp)
random_string 16        # xK9mP2nQ4rS6tU8v

Success and Failure

success "Operation completed"   # Green checkmark
failure "Operation failed"      # Red X

# Exit with message
die 1 "Fatal error occurred"

4. JSON Operations

MAINFRAME provides JSON manipulation without jq.

Creating JSON Objects

# Simple object
json_object "name=John" "city=NYC"
# {"name":"John","city":"NYC"}

# With types
json_object "name=John" "age:number=30" "active:bool=true"
# {"name":"John","age":30,"active":true}

# Nested objects
json_object "user=$(json_object 'name=John' 'age:number=30')"
# {"user":{"name":"John","age":30}}

Creating JSON Arrays

# String array
json_array "apple" "banana" "cherry"
# ["apple","banana","cherry"]

# Number array
json_array_numbers 1 2 3 4 5
# [1,2,3,4,5]

# Mixed types
json_array "hello" "$(json_object 'id:number=1')"
# ["hello",{"id":1}]

Reading JSON

data='{"name":"John","age":30}'

json_get "$data" "name"     # John
json_get "$data" "age"      # 30
json_has "$data" "name"     # returns 0 (true)
json_has "$data" "email"    # returns 1 (false)

Merging JSON

a='{"name":"John"}'
b='{"age":30}'

json_merge "$a" "$b"
# {"name":"John","age":30}

5. String Operations

# Trimming
trim_string "  hello  "           # "hello"
trim_left "  hello"               # "hello"
trim_right "hello  "              # "hello"

# Case conversion
to_lower "HELLO"                  # "hello"
to_upper "hello"                  # "HELLO"
capitalize "hello world"          # "Hello world"
title_case "hello world"          # "Hello World"

# Search and replace
replace_all "a-b-c" "-" "_"       # "a_b_c"
replace_first "a-b-c" "-" "_"     # "a_b-c"
string_contains "hello" "ell"     # returns 0 (true)
starts_with "hello" "hel"         # returns 0 (true)
ends_with "hello" "lo"            # returns 0 (true)

# Splitting
split_string "a,b,c" ","          # Sets SPLIT_RESULT array
echo "${SPLIT_RESULT[0]}"         # "a"

# Length and substring
string_length "hello"             # 5
substring "hello" 1 3             # "ell"

6. Array Operations

declare -a items=("apple" "banana" "apple" "cherry")

# Unique values
unique=($(array_unique "${items[@]}"))
# ("apple" "banana" "cherry")

# Join
array_join "${items[@]}" ", "
# "apple, banana, apple, cherry"

# Contains
array_contains "${items[@]}" "banana"   # returns 0 (true)
array_contains "${items[@]}" "grape"    # returns 1 (false)

# Index
array_index "${items[@]}" "banana"      # 1

# Filter (with function)
is_fruit() { [[ "$1" != "apple" ]]; }
filtered=($(array_filter is_fruit "${items[@]}"))
# ("banana" "cherry")

# Map (with function)
uppercase() { echo "${1^^}"; }
mapped=($(array_map uppercase "${items[@]}"))
# ("APPLE" "BANANA" "APPLE" "CHERRY")

# Sort
sorted=($(array_sort "${items[@]}"))
# ("apple" "apple" "banana" "cherry")

# Reverse
reversed=($(array_reverse "${items[@]}"))
# ("cherry" "apple" "banana" "apple")

7. Date/Time Operations

# Current time
now                               # Unix timestamp: 1705312200
now_iso                           # ISO format: 2024-01-15T10:30:00-0500
timestamp                         # 2024-01-15T10:30:00

# Date arithmetic
date_add $(now) "2d"              # 2 days from now
date_add $(now) "1w"              # 1 week from now
date_subtract $(now) "3h"         # 3 hours ago

# Formatting
format_date $(now) "%Y-%m-%d"     # 2024-01-15
format_relative $epoch            # "2 hours ago", "3 days ago"

# Parsing
parse_date "2024-01-15"           # Unix timestamp

# Comparisons
is_weekend $(now)                 # returns 0 if Saturday/Sunday
is_past $timestamp                # returns 0 if in the past
is_future $timestamp              # returns 0 if in the future

# Durations
format_duration 3661              # "1h 1m 1s"
parse_duration "2h30m"            # 9000 (seconds)

8. File Operations

# File info
file_exists "/path/to/file"       # returns 0 if exists
file_size "/path/to/file"         # Size in bytes
file_lines "/path/to/file"        # Line count
file_ext "/path/to/file.txt"      # "txt"

# Reading
read_file "/path/to/file"         # File contents
head_lines "/path/to/file" 10     # First 10 lines
tail_lines "/path/to/file" 10     # Last 10 lines

# Safe operations (idempotent)
ensure_dir "/path/to/dir"         # Create if not exists
ensure_file "/path/to/file" "content"  # Create with content if not exists

# Atomic operations
atomic_write "/path/to/file" "content"  # Safe write (temp then move)

9. Validation

# Type validation
validate_int "42" 0 100           # Valid integer in range
validate_float "3.14"             # Valid float
validate_bool "true"              # true/false/yes/no/1/0

# Format validation
validate_email "user@example.com" # RFC 5322 simplified
validate_url "https://example.com"
validate_ipv4 "192.168.1.1"
validate_date "2024-01-15"        # YYYY-MM-DD
validate_semver "1.2.3"           # Semantic version

# Path validation (SECURITY)
validate_path_safe "$path" "/base"  # Prevents traversal
validate_filename "report.pdf"      # No path components

# Sanitization
sanitize_shell_arg "$input"       # Safe for shell
sanitize_filename "a/b<c>.txt"    # "a_b_c_.txt"
sanitize_html "<script>alert(1)"  # "&lt;script&gt;alert(1)"

10. For AI Agents

Enable structured JSON output for AI agent parsing:

export MAINFRAME_OUTPUT=json

# Success output
output_success "file created"
# {"ok":true,"data":"file created"}

# Error output
output_error "E_NOT_FOUND" "Config missing" "run init first"
# {"ok":false,"error":{"code":"E_NOT_FOUND","msg":"Config missing","suggestion":"run init first"}}

# Typed output
output_int 42                     # {"ok":true,"data":42}
output_bool true                  # {"ok":true,"data":true}
output_json_object '{"id":1}'     # {"ok":true,"data":{"id":1}}

See USOP Protocol for full documentation.


Next Steps

Goal Page
Explore all functions Library Reference
Build AI agents AI Agent Integration
Secure your scripts Security Best Practices
All function signatures CHEATSHEET.md

MAINFRAME · The AI-Native Bash Runtime

Home · Installation · Library Reference

Clone this wiki locally