Communityライティング&編集github.com

Jamie-BitFlight/bash-portability

This skill should be used when the user asks about "POSIX compatibility", "portable shell scripts", "cross-shell compatibility", "bashisms", "shebang selection", or mentions writing scripts that work on different shells (bash, sh, dash, zsh) or different systems.

bash-portability とは?

bash-portability is a Claude Code agent skill that this skill should be used when the user asks about "POSIX compatibility", "portable shell scripts", "cross-shell compatibility", "bashisms", "shebang selection", or mentions writing scripts that work on different shells (bash, sh, dash, zsh) or different systems.

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Jamie-BitFlight/claude_skills/tree/main/plugins/bash-development/skills/bash-portability

Installed? Explore more ライティング&編集 skills: steipete/notion, obra/writing-skills, obra/executing-plans · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Bash Portability

Guidance for writing portable POSIX-compatible scripts and understanding when to leverage bash-specific features.

Shebang Selection

Use #!/usr/bin/env bash for Bash Scripts

#!/usr/bin/env bash

Why: Searches PATH for bash, works across systems where bash may be in different locations.

Use #!/bin/sh for POSIX Scripts

#!/bin/sh

Why: Maximum portability when bash features aren't needed. On many systems, /bin/sh is dash or another POSIX shell.

Direct Path When Required

#!/bin/bash

Use only when: System requirements guarantee bash location, or security policy requires absolute paths.

POSIX vs Bash Feature Matrix

| Feature | POSIX | Bash | Recommendation | | -------------- | ------- | ---- | ------------------------------ | ---- | | [[ ]] | No | Yes | Use [ ] for POSIX | | (( )) | No | Yes | Use [ ] with -eq etc. | | Arrays | No | Yes | Use positional params or files | | local | Partial | Yes | Generally safe | | ${var,,} | No | 4+ | Use tr for POSIX | | <<< | No | Yes | Use echo | cmd | | =~ regex | No | Yes | Use grep or expr | | source | No | Yes | Use . (dot) command | | function f() | No | Yes | Use f() only | | $'...' | No | Yes | Use printf | | {1..10} | No | Yes | Use seq or while loop |

POSIX-Compatible Patterns

Conditionals

# POSIX - use [ ] with proper quoting
if [ -f "$file" ]; then
    echo "File exists"
fi

# String comparison
if [ "$var" = "value" ]; then
    echo "Match"
fi

# Numeric comparison
if [ "$num" -gt 10 ]; then
    echo "Greater"
fi

# Compound conditions
if [ -f "$file" ] && [ -r "$file" ]; then
    echo "Readable file"
fi

Case Conversion (POSIX)

# Lowercase
lower=$(echo "$string" | tr '[:upper:]' '[:lower:]')

# Uppercase
upper=$(echo "$string" | tr '[:lower:]' '[:upper:]')

Substring Operations (POSIX)

# Get substring - use expr or cut
substr=$(expr "$string" : '.\{3\}\(.\{5\}\)')  # chars 4-8
substr=$(echo "$string" | cut -c4-8)

# String length
length=$(expr length "$string")
length=${#string}  # This is actually POSIX

Reading Files (POSIX)

# Line by line
while IFS= read -r line; do
    echo "$line"
done < "$file"

# Read entire file (without cat)
content=$(cat "$file")  # cat is POSIX

Command Substitution

# Modern syntax (preferred even in POSIX)
result=$(command)

# Legacy syntax (avoid)
result=`command`

# Nested (why modern is better)
result=$(echo $(date))      # Clear
result=`echo \`date\``      # Escape nightmare

Bash-Specific Features Worth Using

When portability isn't required, these bash features improve code quality:

Extended Test [[ ]]

# Pattern matching
[[ "$file" == *.txt ]]

# Regex matching
[[ "$input" =~ ^[0-9]+$ ]]

# No word splitting worries
[[ -f $file ]]  # Quotes optional (but still recommended)

# Logical operators inside
[[ -f "$file" && -r "$file" ]]

Arrays

# Indexed arrays
declare -a files=()
files+=("one.txt")
files+=("two.txt")
for f in "${files[@]}"; do
    process "$f"
done

# Associative arrays (Bash 4+)
declare -A config
config[host]="localhost"
config[port]="8080"

Parameter Expansion

# Default value
"${var:-default}"

# Case conversion (Bash 4+)
"${var,,}"  # lowercase
"${var^^}"  # uppercase

# Substring
"${var:0:10}"  # first 10 chars
"${var: -5}"   # last 5 chars

# Search/replace
"${var//old/new}"

Here Strings

# Bash
read -r var <<< "input string"

# POSIX equivalent
var=$(echo "input string")

Process Substitution

# Bash - compare two command outputs
diff <(sort file1) <(sort file2)

# POSIX equivalent (with temp files)
sort file1 > /tmp/sorted1
sort file2 > /tmp/sorted2
diff /tmp/sorted1 /tmp/sorted2

Detecting Shell Type

# Check if running in bash
if [ -n "${BASH_VERSION:-}" ]; then
    echo "Running in Bash"
fi

# Check bash version for features
if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ]; then
    echo "Bash 4+ available"
fi

# Generic shell detection
case "${SHELL##*/}" in
    bash) echo "bash" ;;
    zsh)  echo "zsh" ;;
    *)    echo "other" ;;
esac

Portable Utility Functions

Code examples

Portability Decision Guide

Use POSIX when:

  • Script runs on minimal systems (containers, embedded)
  • Target includes dash, ash, or busybox sh
  • Maximum compatibility is required
  • Script is part of system initialization

Use Bash when:

  • Target systems guaranteed to have bash
  • Need arrays, associative arrays, or regex
  • Complex string manipulation required
  • Code clarity significantly improved
  • Interactive features needed

Common Portability Pitfalls

echo vs printf

# Problematic - behavior varies
echo -n "no newline"
echo -e "with\ttabs"

# Portable
printf '%s' "no newline"
printf 'with\ttabs\n'

Variable Assignment

# Works everywhere
var="value"

# May fail on some shells
var = "value"  # Spaces around = are wrong

Export with Assignment

# POSIX - separate commands
var="value"
export var

# Bash/modern - combined (works most places)
export var="value"

Array-like Operations Without Arrays

# Use positional parameters
set -- "item1" "item2" "item3"
for item in "$@"; do
    echo "$item"
done

# Or IFS-based splitting
items="item1:item2:item3"
IFS=':' read -r item1 item2 item3 <<EOF
$items
EOF

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

Jamie-BitFlight/agentskill-kaizen-meta-docs

Agentskill kaizen plugin documentation index. Load when needing to read about cross-platform notes, improvement plans, or DuckDB integration.

Jamie-BitFlight/bash-51-features

Bash 5.1 release features and improvements with practical examples. Use when working with Bash 5.1 features, epoch time variables, redirection enhancements, or when user asks about Bash 5.1 changes, new features, or version-specific capabilities.

Jamie-BitFlight/bash-52-features

Bash 5.2 release features and improvements with practical examples. Use when working with Bash 5.2 features, variable handling enhancements, readline improvements, or when user asks about Bash 5.2 changes, new features, or version-specific capabilities.

Jamie-BitFlight/bash-53-features

Bash 5.3 release features and improvements with practical examples. Use when working with Bash 5.3 features, new command substitution, GLOBSORT, loadable builtins, or when user asks about Bash 5.3 changes, new features, or version-specific capabilities.

Jamie-BitFlight/bash-development

This skill should be used when the user asks to "write a bash script", "create a shell script", "implement bash function", "parse arguments in bash", "handle errors in bash", or mentions bash development, shell scripting, script templates, or modern bash patterns.

Jamie-BitFlight/bash-lint

This skill should be used when the user asks to "lint bash script", "run shellcheck", "format shell script", "use shfmt", "fix shellcheck errors", or mentions shell script linting, formatting, code quality, or pre-commit hooks for bash.

Jamie-BitFlight/bash-logging

This skill should be used when the user asks to "add logging to bash script", "colorize output", "implement log levels", "CI/CD sections", "terminal colors in bash", or mentions logging functions, emoji output, collapsible CI sections, or shlocksmith.

Jamie-BitFlight/bash-testing

This skill should be used when the user asks to "test bash script", "write shell tests", "use shunit2", "use shellspec", "create test suite for bash", or mentions unit testing, test frameworks, mocking, or test-driven development for shell scripts.

Jamie-BitFlight/brainstorming-skill

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or when users request help with ideation, marketing, and strategic planning. Explores user intent, requirements, and design before implementation using research-validated prompt patterns.

Jamie-BitFlight/clang-format

Configure clang-format code formatting. Use when: user mentions clang-format or .clang-format, analyzing code style/patterns, creating/modifying formatting config, troubleshooting formatting, brace styles/indentation/spacing/alignment/pointer alignment, or codifying conventions.

Jamie-BitFlight/commitlint

When setting up commit message validation for a project. When project has commitlint.config.js or .commitlintrc files. When configuring CI/CD to enforce commit format. When extracting commit rules for LLM prompt generation. When debugging commit message rejection errors.

Jamie-BitFlight/conventional-commits

When writing a git commit message. When task completes and changes need committing. When project uses semantic-release, commitizen, git-cliff. When choosing between feat/fix/chore/docs types. When indicating breaking changes. When generating changelogs from commit history.

Jamie-BitFlight/dasel-reference

Use when querying, modifying, or converting JSON, YAML, TOML, XML, CSV, HCL, or INI with dasel v3. Complete reference for selectors, functions, conditionals, variables, spread operator, type casting, and format-specific patterns.

Jamie-BitFlight/data-exploration

Use when exploring unknown structured data files with dasel v3 — discover schema, list keys, find nested values, sample arrays, identify data types across JSON, YAML, TOML, XML, CSV, HCL, INI formats

Jamie-BitFlight/data-transformation

Use when modifying, converting, or transforming structured data with dasel v3 — in-place mutations, format conversion, batch operations, array manipulation, object construction, and merge patterns across JSON, YAML, TOML, XML, CSV, HCL, INI

Jamie-BitFlight/delegate

Decompose substantive work into phases, dispatch each phase to a sub-agent, and adjudicate what comes back. Use whenever a request asks for implementation, investigation, a fix, a review, or any change to files — including small ones — and whenever you are about to read source or run a diagnostic yourself instead of handing it off. Also use when a report from a sub-agent needs judging, when a phase needs re-dispatching, or when a user names one instance of a pattern. Does not apply when your own prompt begins "Your ROLE_TYPE is sub-agent." — then follow references/sub-agent-contract.md instead.

Jamie-BitFlight/enterprise-hibernate-hbm

Dasel v3 query patterns for Hibernate .hbm.xml mapping files — entity-table binding, Java property-to-column extraction, one-to-many set/list/bag relationship tracing, many-to-one foreign key discovery, batch scanning across 60+ HBM files. Use when querying Hibernate ORM class mappings, extracting schema metadata from Java persistence layer, or auditing entity-column relationships in enterprise legacy codebases.

Jamie-BitFlight/enterprise-installanywhere

Dasel v3 query patterns for InstallAnywhere .iap_xml installer definitions — use when querying action sequences, discovering variables, resolving platform conditions, navigating panels, or comparing installer variants. Files are 2.5+ MB, 65,000+ lines — too large for context reads, requires structural dasel queries.

Jamie-BitFlight/enterprise-maven-pom

Dasel v3 selector patterns for Maven POM XML files — use when querying dependency versions, filtering by groupId or scope, extracting module hierarchy from parent POMs, or detecting version conflicts across enterprise multi-module Java projects. Load this skill when working with pom.xml files using dasel.

Jamie-BitFlight/enterprise-spring-xml

Dasel v3 selectors for Spring bean factory XML — use when querying any Spring ApplicationContext XML for bean discovery, dependency wiring, JMS destination mapping, property injection extraction, or cross-bean reference tracing. Load this skill before writing dasel selectors against Spring bean XML files (applicationContext.xml, *_beans.xml, spring-*.xml).

関連スキル