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

Bash 移植性ガイド

このスキルは、POSIX互換性、移植可能なシェルスクリプト、クロスシェル互換性、bashism、shebang選択、または異なるシェル(bash、sh、dash、zsh)やシステムで動作するスクリプトの作成についてユーザーが質問した場合に使用します。

Bash 移植性ガイド とは?

このスキルは、ポータブルなPOSIX互換スクリプトの作成と、bash固有の機能をいつ活用すべきかを理解するための包括的なガイダンスを提供します。開発者は、shebangの選択(#!/usr/bin/env bash、#!/bin/sh、#!/bin/bash)や、POSIXとbashの機能マトリックス([[ ]]、配列、local、${var,,}、<<<など)を比較することで、適切なシェル環境を選択できます。また、POSIX互換のパターン(条件分岐、大文字小文字変換、部分文字列操作、ファイル読み取り、コマンド置換)と、bash固有の便利な機能(拡張テスト、配列、パラメータ展開、ヒアドキュメント、プロセス置換)の両方をカバーしています。このスキルは、Claude Code、Cursor、CodexなどのAIエージェントで使用でき、スクリプトが最小限のシステム(コンテナ、組み込み)で動作する必要がある場合や、dash、ash、busybox shをターゲットとする場合に特に役立ちます。最大の互換性が必要な場合や、システム初期化の一部としてスクリプトが使用される場合にも推奨されます。

対応~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, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

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

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

ドキュメント

Bash 移植性ガイド は何をしますか?

ポータブルなPOSIX互換スクリプトを作成し、bash固有の機能をいつ活用すべきかを理解するためのガイダンス。

Shebang 選択

Bash スクリプトには #!/usr/bin/env bash を使用

#!/usr/bin/env bash

理由: PATH から bash を検索するため、bash が異なる場所にあるシステム間でも動作します。

POSIX スクリプトには #!/bin/sh を使用

#!/bin/sh

理由: bash 機能が不要な場合に最大の移植性を提供します。多くのシステムでは、/bin/sh は dash や別の POSIX シェルです。

必要に応じて絶対パスを使用

#!/bin/bash

使用すべき場合: システム要件が bash の場所を保証している場合、またはセキュリティポリシーで絶対パスが必要な場合のみ。

POSIX と Bash の機能マトリックス

機能POSIXBash推奨事項
[[ ]]不可可POSIX では [ ] を使用
(( ))不可可[ ] と -eq などを使用
配列不可可位置パラメータまたはファイルを使用
local一部可一般的には安全
${var,,}不可4+POSIX では tr を使用
<<<不可可`echo
=~ 正規表現不可可grep または expr を使用
source不可可.(ドット)コマンドを使用
function f()不可可f() のみを使用
$'...'不可可printf を使用
{1..10}不可可seq または while ループを使用

POSIX 互換パターン

条件分岐

# POSIX - [ ] を適切な引用符で使用
if [ -f "$file" ]; then
    echo "ファイルが存在します"
fi

# 文字列比較
if [ "$var" = "value" ]; then
    echo "一致"
fi

# 数値比較
if [ "$num" -gt 10 ]; then
    echo "より大きい"
fi

# 複合条件
if [ -f "$file" ] && [ -r "$file" ]; then
    echo "読み取り可能なファイル"
fi

大文字小文字変換(POSIX)

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

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

部分文字列操作(POSIX)

# 部分文字列を取得 - expr または cut を使用
substr=$(expr "$string" : '.\(...\).*')  # 文字列の最初の3文字
substr=$(echo "$string" | cut -c1-3)

# 文字列長
length=$(expr length "$string")
length=${#string}  # これは実際には POSIX です

ファイル読み取り(POSIX)

# 行ごとに
while IFS= read -r line; do
    echo "$line"
done < "$file"

# ファイル全体を読み取り(cat なし)
content=$(cat "$file")  # cat は POSIX です

コマンド置換

# 現代的な構文(POSIX でも推奨)
result=$(command)

# レガシー構文(避ける)
result=`command`

# ネスト(現代的な構文の利点)
result=$(echo $(date))      # 明確
result=`echo \`date\``      # エスケープの悪夢

使用する価値のある Bash 固有機能

移植性が必要ない場合、これらの bash 機能はコード品質を向上させます。

拡張テスト [[ ]]

# パターンマッチング
[[ "$file" == *.txt ]]

# 正規表現マッチング
[[ "$input" =~ ^[0-9]+$ ]]

# 単語分割の心配なし
[[ -f $file ]]  # 引用符は任意(ただし推奨)

# 内部での論理演算子
[[ -f "$file" && -r "$file" ]]

配列

# インデックス配列
declare -a files=()
files+=("one.txt")
files+=("two.txt")
for f in "${files[@]}"; do
    process "$f"
done

# 連想配列(Bash 4+)
declare -A config
config[host]="localhost"
config[port]="8080"

パラメータ展開

# デフォルト値
"${var:-default}"

# 大文字小文字変換(Bash 4+)
"${var,,}"  # 小文字
"${var^^}"  # 大文字

# 部分文字列
"${var:0:10}"  # 最初の10文字
"${var: -5}"   # 最後の5文字

# 検索/置換
"${var//old/new}"

ヒアドキュメント(Here Strings)

# Bash
read -r var <<< "入力文字列"

# POSIX 同等
var=$(echo "入力文字列")

プロセス置換

# Bash - 2つのコマンド出力を比較
diff <(sort file1) <(sort file2)

# POSIX 同等(一時ファイル使用)
sort file1 > /tmp/sorted1
sort file2 > /tmp/sorted2
diff /tmp/sorted1 /tmp/sorted2

シェルタイプの検出

# bash で実行されているか確認
if [ -n "${BASH_VERSION:-}" ]; then
    echo "Bash で実行中"
fi

# 機能のために bash バージョンを確認
if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ]; then
    echo "Bash 4+ 利用可能"
fi

# 汎用シェル検出
case "${SHELL##*/}" in
    bash) echo "bash" ;;
    zsh)  echo "zsh" ;;
    *)    echo "その他" ;;
esac

移植性のあるユーティリティ関数

コード例

移植性判断ガイド

POSIX を使用すべき場合:

  • スクリプトが最小限のシステム(コンテナ、組み込み)で動作する場合
  • ターゲットに dash、ash、busybox sh が含まれる場合
  • 最大の互換性が必要な場合
  • スクリプトがシステム初期化の一部である場合

Bash を使用すべき場合:

  • ターゲットシステムに bash が必ず存在する場合
  • 配列、連想配列、正規表現が必要な場合
  • 複雑な文字列操作が必要な場合
  • コードの可読性が大幅に向上する場合
  • インタラクティブ機能が必要な場合

一般的な移植性の落とし穴

echo vs printf

# 問題あり - 動作が異なる
echo -n "改行なし"
echo -e "タブ\tあり"

# 移植性あり
printf '%s' "改行なし"
printf 'タブ\tあり\n'

変数代入

# どこでも動作
var="value"

# 一部のシェルで失敗する可能性あり
var = "value"  # = の周りにスペースがあると誤り

代入を伴う export

# POSIX - 別々のコマンド
var="value"
export var

# Bash/モダン - 組み合わせ(ほとんどの場所で動作)
export var="value"

配列のない配列的な操作

# 位置パラメータを使用
set -- "item1" "item2" "item3"
for item in "$@"; do
    echo "$item"
done

# または IFS ベースの分割
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).

関連スキル