Shell scripting toolkit with Google Style Guide refactoring and Unix man page expertise

version
1.0.0

Install

/plugin install shell@dot-claude

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pproenca/dot-claude-old.

Contents

Discovered from source

Skills 2

Google Shell Style Guide

Apply consistent, safe, and readable shell scripting practices based on Google's Shell Style Guide.

Core Principles

  1. Consistency - Follow existing style in files being modified
  2. Safety - Quote variables, use [[ ]], avoid eval
  3. Readability - 2-space indent, 80-char lines, clear naming

Quick Reference

RuleDoAvoid
Command substitution$(command)`command`
Tests[[ condition ]][ condition ] or test
Arithmetic(( x + y ))let, expr, $[ ]
Variables"${var}"$var or ${var} unquoted
Functionsfunc_name() {function func_name {
Indentation2 spacesTabs

Formatting Rules

Indentation

Use 2 spaces. Never tabs (exception: heredoc with <<-).

if [[ -n "${var}" ]]; then
  echo "indented with 2 spaces"
fi

Line Length

Maximum 80 characters. For long strings, use heredocs or embedded newlines:

cat <<EOF
Long string content
spanning multiple lines
EOF

long_string="First line
second line"

Pipelines

One line if fits, otherwise split with pipe on new line:

command1 | command2

command1 \
  | command2 \
  | command3

Control Flow

Put ; then and ; do on same line as if/for/while:

if [[ -d "${dir}" ]]; then
  process_dir
fi

for file in "${files[@]}"; do
  process_file "${file}"
done

while read -r line; do
  echo "${line}"
done < input.txt

Case Statements

Indent alternatives by 2 spaces. Simple cases on one line:

case "${option}" in
  a) action_a ;;
  b) action_b ;;
  complex)
    do_something
    do_more
    ;;
  *)
    error "Unknown option"
    ;;
esac

Variable Handling

Quoting

Always quote strings containing variables, command substitutions, or special characters:

flag="$(some_command)"
echo "${flag}"
grep -li Hugo /dev/null "$1"

Variable Expansion

Prefer "${var}" with braces. Exception: single-character positional params ($1, $@):

echo "PATH=${PATH}, file=${filename}"
echo "Positional: $1 $2 $3"
echo "All args: $@"

Arrays

Use arrays for lists, especially command arguments:

declare -a flags
flags=(--foo --bar='baz')
flags+=(--config="${config_file}")
mybinary "${flags[@]}"

Command Substitution and Tests

Command Substitution

Always use $(command), never backticks:

var="$(command "$(nested_command)")"

Tests

Use [[ ]] for all tests. Use -z/-n for string checks, (( )) for numeric:

if [[ -z "${my_var}" ]]; then
  echo "empty"
fi

if [[ "${my_var}" == "value" ]]; then
  echo "match"
fi

if (( count > 10 )); then
  echo "large"
fi

Arithmetic

Use (( )) or $(( )). Never let, expr, or $[ ]:

(( i += 3 ))
result=$(( x * y + z ))

if (( a < b )); then
  echo "a is smaller"
fi

Naming Conventions

Functions

Lowercase with underscores. Braces on same line:

my_function() {
  local result
  result="$(do_work)"
  echo "${result}"
}

mypackage::helper() {
  # namespaced function
}

Variables

Lowercase with underscores for local variables:

local file_name
local -i count=0

Constants

Uppercase with underscores. Use readonly:

readonly CONFIG_PATH='/etc/app/config'
declare -xr EXPORTED_VAR='value'

Script Structure

Function Location

Put all functions near top, after constants. No executable code between functions.

Main Function

Scripts with multiple functions must have a main function:

#!/bin/bash

readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

helper_func() {
  # helper implementation
}

main() {
  local arg="$1"
  helper_func "${arg}"
}

main "$@"

Local Variables

Always declare function variables as local. Separate declaration from command substitution:

my_func() {
  local name="$1"
  local result
  result="$(some_command)"
  (( $? == 0 )) || return 1
  echo "${result}"
}

Common Anti-Patterns

Avoid eval

eval $(set_my_variables)

Avoid Aliases in Scripts

Use functions instead:

fancy_ls() {
  ls -lh "$@"
}

Avoid Pipes to While

Use process substitution to preserve variables:

while read -r line; do
  last_line="${line}"
done < <(your_command)

Avoid mapfile/readarray (macOS Incompatible)

mapfile and readarray are Bash 4+ builtins not available on macOS (Bash 3.2). Use while read loop instead:

# AVOID - fails on macOS
mapfile -t files < <(find . -name "*.txt")

# USE - portable
files=()
while IFS= read -r file; do
  files+=("$file")
done < <(find . -name "*.txt")

Wildcard Safety

Use explicit path prefix:

rm -v ./*

Error Handling

Check Return Values

if ! mv "${files[@]}" "${dest}/"; then
  echo "Move failed" >&2
  exit 1
fi

PIPESTATUS

Check pipeline component failures:

tar -cf - ./* | ( cd "${dir}" && tar -xf - )
if (( PIPESTATUS[0] != 0 || PIPESTATUS[1] != 0 )); then
  echo "Pipeline failed" >&2
fi

Security Patterns

Safe Temporary Files

Always use mktemp with trap cleanup:

cleanup() {
  local exit_code=$?
  [[ -n "${TEMP_FILE:-}" ]] && rm -f "${TEMP_FILE}"
  exit "${exit_code}"
}
trap cleanup EXIT

TEMP_FILE="$(mktemp)"
# use TEMP_FILE...

Input Validation

Validate user input before use:

validate_path() {
  local path="$1"
  # Reject empty
  [[ -z "${path}" ]] && return 1
  # Reject path traversal
  [[ "${path}" == *..* ]] && return 1
  # Require within allowed directory
  [[ "${path}" != "${ALLOWED_DIR}"/* ]] && return 1
  return 0
}

Command Injection Prevention

Never use eval with external input. Use arrays for dynamic commands:

# DANGEROUS - injection risk
eval "${user_command}"

# SAFE - use arrays
declare -a cmd_args
cmd_args=("--flag" "${user_input}")
mycommand "${cmd_args[@]}"

Always quote variable expansions in commands:

# DANGEROUS
rm $file_path
grep $pattern $file

# SAFE
rm -- "${file_path}"
grep -- "${pattern}" "${file}"

Use -- to prevent option injection with user-provided filenames.

Issue Severity Classification

For shell-expert agent reviews, issues are classified as:

Critical (Must Fix)

  • Unquoted variables in rm, mv, or path operations
  • Use of eval with external input
  • Missing error handling on destructive operations
  • Command injection vulnerabilities

Important (Should Fix)

  • Using [ ] instead of [[ ]]
  • Missing local in functions
  • Backticks instead of $()
  • Missing main function in multi-function scripts

Minor (Suggestions)

  • Inconsistent indentation
  • Long lines (> 80 chars)
  • Missing braces on simple variables
  • Comment formatting

Additional Resources

For the complete Google Shell Style Guide, see: https://google.github.io/styleguide/shellguide.html

Unix Man Pages (Non-Interactive)

Consult system manual pages for accurate command documentation. Prefer man pages over training data when precision matters.

CRITICAL: Never run bare man <command> - it opens an interactive pager that hangs.

How to Use Efficiently

Follow these rules to avoid flooding your context window:

  1. Search first - If unsure of the command name, use mancat -k <keyword>
  2. Target sections - Don't fetch the full man page immediately:
    • Read SYNOPSIS first to understand the structure
    • Read DESCRIPTION for a high-level overview
    • Fetch OPTIONS only when you need specific flags
  3. Sanitization is automatic - The mancat tool strips formatting codes; raw control characters are handled

Usage Workflows

A. Discovery (Instead of Web Search)

When you don't know which command to use:

# CLAUDE_PLUGIN_ROOT is set automatically by Claude Code plugins
MANCAT="${CLAUDE_PLUGIN_ROOT}/skills/man/mancat.sh"
"$MANCAT" -k compress    # Returns: gzip, bzip2, tar, zip with descriptions
"$MANCAT" -k "file system"

B. Syntax Verification

When you know the command but need exact argument order:

"$MANCAT" -s SYNOPSIS tar
# Output: tar [-] A --catenate --concatenate | c --create | d --diff ...

C. Flag Investigation

When you need to understand a specific option:

"$MANCAT" -s OPTIONS tar
# Or for a specific flag:
"$MANCAT" tar | grep -A5 -- '-z'

Quick Start

# Use the mancat helper (recommended)
"${CLAUDE_PLUGIN_ROOT}/skills/man/mancat.sh" ls

# Or pipe through col -b
man ls | col -b

The mancat Helper

Use the included mancat.sh for convenient non-interactive access:

MANCAT="${CLAUDE_PLUGIN_ROOT}/skills/man/mancat.sh"

"$MANCAT" ls                 # Full man page, clean output
"$MANCAT" passwd 5           # Section 5 (file formats)
"$MANCAT" -s OPTIONS tar     # Extract just OPTIONS section
"$MANCAT" -k compress        # Search descriptions (apropos)

Manual Non-Interactive Patterns

Use these raw patterns when mancat.sh is unavailable or when piping to tools like grep/sed:

man <command> | col -b

The col -b filter strips backspace formatting codes, producing clean plain text.

Alternatives:

PAGER=cat man <command>    # Force no pager (may include escape codes)
man <command> | cat        # Simple but less clean on some systems

Efficient Lookups (Raw Patterns)

Full man pages waste context. Use targeted extraction with grep/sed:

Get Specific Option

man tar | col -b | grep -A5 -- '-z'
man curl | col -b | grep -A8 -- '--data'

Extract Section

# SYNOPSIS section
man ls | col -b | sed -n '/^SYNOPSIS/,/^[A-Z]/p' | head -20

# OPTIONS section (first 50 lines)
man curl | col -b | sed -n '/^OPTIONS/,/^[A-Z]/p' | head -50

# EXAMPLES section
man rsync | col -b | sed -n '/^EXAMPLES/,/^[A-Z]/p'

Limit Output Length

Always limit long pages:

man bash | col -b | head -100
man git-rebase | col -b | head -150

Quick Reference Commands

Search for Commands

man -k <keyword>              # Search names and descriptions
man -k compress | head -10    # Find compression tools
man -k "file system"          # Search phrase

One-Line Description

man -f tar
# tar (1) - manipulate tape archives

Check Man Page Exists

man -w grep >/dev/null 2>&1 && echo "has man page"

Get Man Page Path

man -w ls
# /usr/share/man/man1/ls.1

Man Page Sections

SectionContent
1User commands
2System calls
3Library functions
4Special files (/dev)
5File formats (/etc/passwd)
6Games
7Miscellaneous (protocols, conventions)
8System administration commands

Specify section when a name exists in multiple:

man 1 printf | col -b   # Shell command
man 3 printf | col -b   # C library function
man 5 crontab | col -b  # File format
man 8 cron | col -b     # Daemon

Reading Man Output

SYNOPSIS - Command syntax. [] = optional, ... = repeatable.

OPTIONS - Flag descriptions with exact syntax.

EXAMPLES - Working command examples (not all pages have these).

SEE ALSO - Related commands worth checking.

When to Use Man Pages

  • System commands (ls, find, tar) - Options vary by OS
  • Config files (man 5 sudoers) - Syntax documentation
  • Git subcommands (man git-rebase) - Full option reference
  • Network tools (man curl, man ssh) - Protocol-specific flags

Commands 1

Refactor Shell Script to Google Style Guide

Refactor the specified shell script to follow Google Shell Style Guide.

Progress Tracking

Create TodoWrite with each step:

  1. Identify and read target script
  2. Analyze (shellcheck + shell-expert in parallel)
  3. Propose changes
  4. Apply refactoring
  5. Verify and report

Step 1: Identify and Read Target Script

If $ARGUMENTS is provided, use it as the target script path.

Otherwise, find shell scripts and prompt user:

fd -e sh -e bash --type f 2>/dev/null | head -20

Use AskUserQuestion:

  • Header: "Script"
  • Question: "Which shell script would you like to refactor?"
  • Options: [up to 4 scripts from fd results]

Read the script content to understand its structure.

Step 2: Analyze

Run these in parallel:

Shellcheck

shellcheck -f gcc "<target_script_path>" 2>&1 || true

If shellcheck not installed, note: brew install shellcheck (macOS) or apt install shellcheck (Linux).

Shell-expert dispatch

Task tool with:
- subagent_type: "shell:shell-expert"
- prompt: "REVIEW the shell script at <target_script_path>"

Load style guide

Skill tool with: skill: "shell:google-shell-style"

Combine findings from shellcheck and shell-expert. For each violation note:

  • Line number
  • Current code
  • Recommended fix
  • Rule reference

Step 3: Propose Changes

Present summary:

  • Total violations: N
  • Critical fixes: N
  • Style improvements: N

Use AskUserQuestion:

  • Header: "Refactor"
  • Question: "How would you like to proceed?"
  • Options:
    • Apply all: Apply all changes
    • Critical only: Only apply critical fixes
    • Cancel: Do not make changes

Step 4: Apply Refactoring

Use Edit tool to apply approved changes in order:

  1. Critical fixes (security, correctness)
  2. Structural changes (main function, organization)
  3. Style improvements (formatting, quoting)

Step 5: Verify and Report

Syntax check

bash -n "<target_script_path>"

Shellcheck comparison

shellcheck -f gcc "<target_script_path>" 2>&1 || true

Compare with baseline - refactoring should reduce issues.

Final Report

## Refactoring Complete

**File:** [path]

### Changes Applied
- [key changes by category]

### Shellcheck Comparison
| Metric | Before | After | Delta |
|--------|--------|-------|-------|
| Errors | N | N | -N |
| Warnings | N | N | -N |

### Verification
- Syntax check: [PASS/FAIL]
- Shellcheck delta: [Improved/Same/Regressed]

### Shell Expert Assessment
- **Initial Review:** [summary]
- **Recommendation:** [PASS/NEEDS_FIXES]

Agents 1

You are a Senior Shell Scripting Expert. Your first action is to load the style guide:

Use Skill tool with: skill: "shell:google-shell-style"

This provides all formatting rules, security patterns, and severity classifications.

Input Handling

When dispatched, you will receive:

  1. A script path (e.g., "REVIEW the shell script at /path/to/script.sh")
  2. A mode indicator: REVIEW, QUICK_REVIEW, SECURITY, or POSIX

Your first actions:

  1. Load the google-shell-style skill (as shown above)
  2. Read the script file
  3. Confirm path and line count
  4. Proceed with mode-specific analysis

If no path is provided: Ask for clarification.

Mode Selection

ModeTriggers
REVIEW"review", "check style", "audit", "refactor"
QUICK_REVIEW"quick review", "validate", "verify"
SECURITY"security", "injection", "safe", "untrusted", "eval"
POSIX"portable", "POSIX", "sh", "dash", "alpine", "busybox"

REVIEW Mode

Analyze script through these lenses:

  1. Understanding: Purpose, inputs, outputs
  2. Structure: main function, function organization, no code between definitions
  3. Safety: Variable quoting, eval usage, input handling
  4. Style: Apply rules from google-shell-style skill

Early Exit: Simple scripts (< 50 lines, no functions) with no Critical issues → PASS with HIGH confidence.

Output Format

### Review Summary
[1-2 sentences: path, purpose, line count, impression]

### Issues by Severity

#### Critical (Must Fix)
- **Line X:** [issue] - [why] - [fix]

#### Important (Should Fix)
- **Line X:** [issue] - [fix]

#### Minor (Suggestions)
- **Line X:** [suggestion]

### Assessment
**Recommendation:** [PASS / NEEDS_FIXES / CRITICAL_ISSUES]
**Confidence:** [HIGH / MODERATE / LOW]
**Reasoning:** [2-3 sentences]

QUICK_REVIEW Mode

Fast validation - scan for Critical issues only:

  • Unquoted variables in rm, mv, or path operations
  • eval with external input
  • Missing error handling on destructive operations

Output (clean): **Quick Review:** PASS ✓ - No critical issues in [name] ([N] lines).

Output (issues): List critical issues with line numbers and fixes.

SECURITY Mode

Analyze:

  1. Input vectors: args, stdin, env, files
  2. Injection risks: eval, unquoted expansions, source with variables
  3. Resource safety: temp files (mktemp + trap), permissions
  4. Error paths: Do failures expose sensitive info?

Output Format

### Security Assessment: [script name]

**Input Vectors:** [list sources]

### Findings by Severity
#### Critical (Exploitable)
#### Warning (Risky Pattern)
#### Info (Hardening Opportunity)

### Secure Patterns Found
[Good practices already in use]

### Assessment
**Security Status:** [SECURE / NEEDS_HARDENING / VULNERABLE]
**Confidence:** [HIGH / MODERATE / LOW]

POSIX Mode

Check for bashisms:

  • [[ ]] → [ ] with quoting
  • Arrays → not POSIX
  • ${var//pat/rep} → sed
  • source → .
  • function f {} → f() {}
  • <<< here-strings → echo | pipe
  • <() process substitution → temp files

Output Format

### POSIX Compatibility Report: [script name]

**Current Shell:** [shebang]
**Target Shell:** [sh/dash/busybox]

### Bashisms Found
| Line | Bashism | POSIX Alternative |
|------|---------|-------------------|

### Assessment
**POSIX Compliance:** [COMPLIANT / NEEDS_CHANGES / NOT_PORTABLE]
**Effort to Fix:** [LOW / MEDIUM / HIGH]

Pre-Output Checklist

  • Every issue has a specific line number
  • Critical issues are truly critical (security/correctness, not style)
  • Provided specific fixes, not just "fix this"
  • Recommendation matches findings

Sponsors

Details

Marketplace
pproenca/dot-claude-old
Source
plugins/domain/shell
Category
Community
License
MIT
Keywords
shell, bash, style, refactor, google, man, unix, manual

More from pproenca/dot-claude-old

All 12