Skip to main content
All scripts in TheTeleporter Scripts collection follow consistent standards and conventions. These guidelines ensure reliability, maintainability, and a uniform user experience.

Core Standards

Every script must include these essential elements:

1. Bash Shebang

All scripts must start with a bash shebang:
#!/bin/bash
For scripts that need specific bash features, you can use:
#!/usr/bin/env bash
Use #!/usr/bin/env bash when you need bash 4.0+ features or want better portability across systems.

2. Documentation Header

Include a comprehensive header at the top of every script:
#!/bin/bash
# script-name.sh - Brief description of what this script does
#
# Usage:
#   ./script-name.sh [OPTIONS] [ARGS]
#
# Options:
#   -h, --help      Show this help message
#   -d, --debug     Enable debug mode
#   -v, --verbose   Verbose output
#
# Examples:
#   ./script-name.sh
#   ./script-name.sh --debug
The header should include:
  • Script name and brief description
  • Usage syntax
  • Available options
  • Example commands

3. Error Handling

Use set -eo pipefail for robust error handling:
set -eo pipefail
What each flag does:
  • -e: Exit immediately if any command fails
  • -o pipefail: Return exit code of first failed command in pipeline
Some interactive scripts may use set -o pipefail without -e to handle errors more gracefully. This is acceptable when the script needs fine-grained error control.

4. Help Flag

Every script must support the --help flag:
show_help() {
  cat << EOF
${BOLD}${CYAN}script-name.sh${NC} - Brief description

${BOLD}USAGE:${NC}
  ./script-name.sh [OPTIONS] [ARGS]

${BOLD}OPTIONS:${NC}
  ${GREEN}-h, --help${NC}      Show this help message
  ${GREEN}-d, --debug${NC}     Enable debug mode

${BOLD}EXAMPLES:${NC}
  ${DIM}# Basic usage${NC}
  ./script-name.sh

EOF
  exit 0
}

5. Executable Permissions

All scripts must be executable:
chmod +x script-name.sh

Color Standards

Use consistent color coding for output messages:
# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m' # No Color

Color Usage Guidelines

ColorUse CaseFunctionExample
RedErrors, failureserror()error "File not found"
GreenSuccess, completionsuccess()success "Upload complete"
YellowWarnings, cautionswarning()warning "Large file size"
BlueInfo, progresslog()log "Processing..."
CyanHeaders, titlesHelp text${CYAN}Script Name${NC}
MagentaSpecial infoCustomecho -e "${MAGENTA}Note${NC}"
DimDebug, commentsdebug()debug "Variable: $VAR"

Standard Logging Functions

Implement these logging functions in every script:
log() {
  echo -e "${BLUE}ℹ${NC} $*"
}

success() {
  echo -e "${GREEN}✓${NC} $*"
}

error() {
  echo -e "${RED}✗${NC} $*" >&2
}

warning() {
  echo -e "${YELLOW}⚠${NC} $*"
}

debug() {
  if [[ $DEBUG -eq 1 ]]; then
    echo -e "${DIM}[DEBUG]${NC} $*"
  fi
}
Important: Error messages should be written to stderr using >&2 to allow proper output redirection.

Argument Parsing

Use a consistent argument parsing pattern:
# Configuration
DEBUG=0
VERBOSE=0

# Argument parsing
while [[ $# -gt 0 ]]; do
  case $1 in
    -h|--help)
      show_help
      ;;
    -d|--debug)
      DEBUG=1
      shift
      ;;
    -v|--verbose)
      VERBOSE=1
      shift
      ;;
    *)
      error "Unknown option: $1"
      echo "Use --help for usage information"
      exit 1
      ;;
  esac
done

Standard Options

These options should be supported by all scripts:
  • -h, --help - Display help message
  • -d, --debug - Enable debug mode (dry-run)
  • -v, --verbose - Enable verbose output

Code Organization

Organize script sections in this order:
#!/bin/bash
# Header with documentation

set -eo pipefail

# ==================== COLORS ====================
# Color definitions

# ==================== CONFIGURATION ====================
# Script configuration variables

# ==================== FUNCTIONS ====================
# Helper functions

# ==================== ARG PARSING ====================
# Command-line argument parsing

# ==================== MAIN LOGIC ====================
# Main script logic

# ==================== EXECUTION ====================
# Script entry point

Debug Mode

All scripts should support a debug mode that:
  1. Shows what would be executed without making changes
  2. Prints debug messages
  3. Can be enabled with --debug flag
if [[ $DEBUG -eq 1 ]]; then
  debug "Would execute: rm -rf /tmp/cache"
  warning "This is a dry-run, no changes will be made"
else
  rm -rf /tmp/cache
  success "Cache cleared"
fi

File Structure Standards

Naming Conventions

  • Use lowercase with hyphens: backup-files.sh
  • Use underscores for multi-word scripts: gdrive_ingest.sh
  • Use .sh extension for all bash scripts

Directory Organization

scripts/
├── cloud/              # Cloud storage integrations
├── system/             # System utilities
├── templates/          # Script templates
└── README.md
Group related scripts by category:
  • cloud/ - Cloud storage services
  • system/ - System utilities and automation
  • templates/ - Script templates

Configuration Files

For scripts that need configuration:
  1. Use .env files for sensitive data:
ENV_FILE="$SCRIPT_DIR/.env"

if [[ -f "$ENV_FILE" ]]; then
  set -a
  source "$ENV_FILE"
  set +a
else
  error ".env file not found"
  exit 1
fi
  1. Provide .env.example template:
# .env.example
API_KEY=your_api_key_here
API_SECRET=your_api_secret_here
  1. Validate required variables:
if [[ -z "$API_KEY" ]] || [[ -z "$API_SECRET" ]]; then
  error "Missing credentials in .env file"
  exit 1
fi

Documentation Standards

Each script or project should have:
  1. Inline comments for complex logic
  2. README.md for projects with multiple files
  3. Help text accessible via --help
  4. Usage examples in header and help text

Error Messages

Write clear, actionable error messages:
# Bad
error "Error"

# Good
error "File not found: $FILE"
error "Missing required argument: --source"
error "Permission denied: Cannot write to $DIR"
Include:
  • What went wrong
  • What was expected
  • How to fix it (when applicable)

Exit Codes

Use standard exit codes:
  • 0 - Success
  • 1 - General error
  • 2 - Misuse of command (invalid arguments)
if [[ -z "$REQUIRED_ARG" ]]; then
  error "Missing required argument"
  exit 2
fi

if ! command -v jq &>/dev/null; then
  error "jq is not installed"
  exit 1
fi

Best Practices

1. Validate Dependencies

if ! command -v curl &>/dev/null; then
  error "curl is not installed"
  exit 1
fi

2. Use Quotes

Always quote variables to prevent word splitting:
# Bad
rm -rf $DIR

# Good
rm -rf "$DIR"

3. Check File Existence

if [[ ! -f "$FILE" ]]; then
  error "File not found: $FILE"
  exit 1
fi

4. Cleanup on Exit

Use traps for cleanup:
cleanup() {
  rm -rf "$TEMP_DIR"
  show_cursor
}
trap cleanup EXIT INT TERM

Examples from Real Scripts

gdrive_ingest.sh

Shows advanced features:
  • Configuration loading from .env
  • Interactive UI with cursor control
  • Trap handlers for cleanup
  • Multiple output functions

power_guard.sh

Shows minimal script:
  • Simple utility script
  • Basic structure without template complexity
  • Direct implementation

Checklist

Before committing a script, verify:
  • Bash shebang present
  • Documentation header complete
  • Help flag implemented
  • Error handling with set -eo pipefail
  • Color-coded output
  • Logging functions (log, success, error, warning, debug)
  • Debug mode support
  • Argument parsing with validation
  • Executable permissions set
  • Syntax validated with bash -n
  • README or inline documentation

Next Steps

  • Read Creating Scripts to build your first script
  • Learn Testing approaches to validate your code
  • Browse existing scripts for examples and patterns

Build docs developers (and LLMs) love