Skip to content

@elad12390/bash-cli-refactoring

1.0.0

Refactor bash CLI tools systematically. Helper extraction, god function decomposition, bash gotchas (set -e, local masking, ANSI-C quoting), BDD testing with pytest-bdd, command patterns, and a 9-item anti-pattern catalog. Triggers: refactor bash, bash CLI, shell script refactoring, bash best practices, bash anti-patterns, bash god function, BDD bash, test bash CLI, bash set -e, bash debugging, shell script patterns, bash code quality, bash cleanup, refactoring CLI tool


name: bash-cli-refactoring description: | Refactor bash CLI tools systematically using BDD methodology. Covers helper extraction (debug-aware wrappers, interactive pickers, two-tier resolution), god function decomposition (orchestrator pattern, extraction by concern), bash-specific gotchas (set -e traps, local masking, ANSI-C quoting, pipefail), BDD testing for bash (pytest-bdd with subprocess runner, testing without external dependencies), standard command patterns (entry point architecture, two-path flow, argument parsing), and a 9-item anti-pattern catalog with detection signals and fix recipes. Synthesized from real refactoring of a 1500-line kubectl wrapper CLI.

Trigger phrases: "refactor bash", "bash CLI", "shell script refactoring", "bash refactor", "refactor shell script", "bash best practices", "shell script quality", "bash anti-patterns", "bash god function", "bash helper extraction", "BDD bash", "test bash CLI", "bash cleanup", "bash set -e", "bash debugging", "refactoring CLI tool", "bash code quality", "shell script patterns", "bash code review"

Bash CLI Refactoring

Systematic methodology for refactoring bash CLI tools, synthesized from real refactoring of a 1500-line Kubernetes CLI wrapper.

Core Philosophy

  1. Extract by duplication, decompose by concern — Helper extraction eliminates repeated code. God function decomposition separates concerns. Different triggers, different techniques.
  2. Two-tier resolution — Pure resolve functions return values or empty. Ensure functions add interactive fallback. Never mix side effects with logic.
  3. BDD before refactoring — Write tests for existing behavior first. Then refactor with confidence. pytest-bdd + subprocess = zero mocks.
  4. Bash has landmineslocal masks exit codes, set -o pipefail breaks grep, single-quoted ANSI codes are literal strings. Know the gotchas.
  5. Fix anti-patterns, not symptoms — A 9-item catalog with detection signals. Grep for the pattern, apply the recipe.

Quick-Start: Common Problems

"This 200-line function does everything"

  1. Identify concerns: arg parsing, resolution, data transform, output, tool logic
  2. Name each concern as _module_action()
  3. Extract one at a time, test after each extraction
  4. Keep orchestrator thin (~50 lines) -> See references/god-function-decomposition.md

"Same 7 lines copy-pasted in every command"

  1. Identify the repeated pattern (selection, resolution, cleanup)
  2. Extract to a helper with edge case handling
  3. Choose naming: _fzf_select (infra), select_resource (domain), ensure_pod (resolution)
  4. Replace all occurrences, test each one -> See references/helper-extraction.md

"How do I test a CLI that needs a Kubernetes cluster?"

  1. Set up .bdd/ directory with pytest-bdd
  2. Write subprocess-based CLI runner with ANSI stripping
  3. Test what does NOT need the cluster: help, validation, routing, error messages
  4. Test command routing via expected output headers -> See references/bdd-for-bash.md

"I'm refactoring and things keep breaking silently"

  1. Check for local var=$(cmd) — masks exit codes
  2. Check ANSI quoting: use $'\033[1m' not '\033[1m'
  3. Check set -e is in ALL sourced library files
  4. Do NOT add set -o pipefail if using grep in pipelines -> See references/bash-gotchas.md

"Where do I even start with this messy CLI?"

  1. Run the anti-pattern detection grep commands
  2. Prioritize: blind stderr suppression > duplication > god functions
  3. Add BDD tests for existing behavior first
  4. Refactor one anti-pattern at a time -> See references/anti-pattern-catalog.md

Decision Trees

What to Refactor First

SignalPriorityAction
2>/dev/null on data-fetching callsHighDebug-aware wrapper
Same 5+ lines in 3+ commandsHighHelper extraction
Function >100 linesMediumGod function decomposition
No set -e in library filesMediumAdd to all files
No testsMediumBDD test suite first
Hardcoded credentialsLowEnv var override
Dead codeLowRemove + update routing

Extraction Type Selection

PatternTechniqueReference
Same code in multiple commandsHelper extractionreferences/helper-extraction.md
One huge function, many concernsGod function decompositionreferences/god-function-decomposition.md
Repeated interactive selectionGeneric picker + domain layerreferences/helper-extraction.md
Repeated resource resolutionTwo-tier resolve/ensurereferences/helper-extraction.md
Missing validationRegex guard patternreferences/anti-pattern-catalog.md

Communication Between Bash Functions

Data TypeMechanismExample
Return valuesstdoutlocal ns=$(resolve_namespace "$app")
ConfigurationGlobal variables_LOGS_FOLLOW="-f" set by orchestrator
Input parametersFunction arguments_logs_stream_stern "$namespace" "${apps[@]}"
Error signalingReturn code + stderrprint_error "msg" >&2; return 1
Status messagesstderrprint_warning "msg" >&2

Reference Files

FileContents
references/helper-extraction.mdDebug-aware wrappers, interactive pickers, two-tier resolution, cleanup patterns — when and how to extract reusable helpers
references/god-function-decomposition.mdOrchestrator pattern, extraction by concern, naming conventions, step-by-step decomposition procedure
references/bash-gotchas.mdset -e traps, local masking exit codes, pipefail vs grep, ANSI-C quoting, heredoc escaping, array handling, subshell scope
references/bdd-for-bash.mdpytest-bdd setup for CLIs, subprocess runner with ANSI stripping, testing without external dependencies, feature file categories
references/command-patterns.mdEntry point architecture, standard cmd_* pattern, two-path flow, argument parsing, library module organization, help system, debug mode
references/anti-pattern-catalog.md9 anti-patterns with detection signals, fix recipes, before/after code, and grep-based detection commands

Command Palette

Search skills, docs, and navigate Tank