Communityコーディング&開発github.com

Jamie-BitFlight/bash-51-features

Bash 5.1 リリースの機能と改善点を実用的な例と共に紹介します。Bash 5.1 の機能、エポック時間変数、リダイレクトの拡張、またはユーザーが Bash 5.1 の変更点、新機能、バージョン固有の機能について質問した場合に使用します。

bash-51-features とは?

このスキルは、Bash 5.1 で導入された新機能と改善点を、実用的なコード例と共に詳しく解説します。主なトピックとして、`EPOCHSECONDS` や `EPOCHREALTIME` といった新しいシェル変数、暗号学的に強力な乱数を生成する `SRANDOM`、ファイルディスクリプタの管理を改善する `{varname}` リダイレクト構文、連想配列の強化、Readline 8.1 の統合、シグナルハンドリングの改善などが含まれます。各機能について、具体的な使用例やベストプラクティスが示されており、Bash 5.1 を最大限に活用したい開発者にとって有用です。また、バージョンチェックの方法や下位互換性に関する注意点も提供されており、既存のスクリプトを最新バージョンに移行する際のガイドとしても役立ちます。

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

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

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

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

ドキュメント

Bash 5.1 の機能と改善点

2020年12月にリリースされたBash 5.1は、最新のシェルスクリプティング向けにいくつかの注目すべき機能と改善を導入しました。

新しいシェル変数

EPOCHSECONDS と EPOCHREALTIME

現在時刻にアクセスするための2つの新しい特殊変数:

# 現在のUnixタイムスタンプ(秒)を取得
echo "現在のタイムスタンプ: ${EPOCHSECONDS}"

# マイクロ秒精度で現在のUnixタイムスタンプを取得
echo "高精度タイムスタンプ: ${EPOCHREALTIME}"

# 実用的な例: シンプルなベンチマーク
start="${EPOCHREALTIME}"
# ... 何らかの処理 ...
sleep 0.5
end="${EPOCHREALTIME}"
duration=$(awk "BEGIN {print ${end} - ${start}}")
echo "処理にかかった時間: ${duration} 秒"

# 例: 高精度タイムスタンプ付きでログ出力
log_message() {
    printf '[%s.%06d] %s\n' \
        "$(date -d "@${EPOCHSECONDS}" '+%Y-%m-%d %H:%M:%S')" \
        "${EPOCHREALTIME#*.}" \
        "$*"
}

log_message "プロセスを開始"

使用例:

  • 正確なパフォーマンス計測
  • ログ出力用の高解像度タイムスタンプ
  • 外部の date コマンド呼び出しの回避
  • スクリプト内でのマイクロ秒精度のタイミング

SRANDOM 変数

暗号学的に強力な乱数:

# 安全な乱数を生成(利用可能な場合)
if [[ -n "${SRANDOM}" ]]; then
    secure_random="${SRANDOM}"
    echo "安全な乱数: ${secure_random}"
else
    echo "SRANDOM は利用できません(getrandom/getentropy が必要です)"
fi

# 実用的な例: 安全な乱数名で一時ファイルを生成
temp_file="/tmp/secure_${SRANDOM}_${EPOCHSECONDS}.tmp"

注意: SRANDOM を使用するには、システムが getrandom() または getentropy() システムコールをサポートしている必要があります。

改善されたリダイレクト構文

{varname} リダイレクト

ファイルディスクリプタを変数に割り当て、ファイルハンドルの管理を改善:

# ファイルディスクリプタを開き変数に格納
exec {fd}< input.txt
while IFS= read -r -u "${fd}" line; do
    echo "読み取り: ${line}"
done
exec {fd}<&-  # ファイルディスクリプタを閉じる

# 実用的な例: 複数のファイルハンドル
exec {input_fd}< data.txt
exec {output_fd}> results.txt
exec {error_fd}> errors.txt

process_data() {
    while IFS= read -r -u "${input_fd}" line; do
        if validate_line "${line}"; then
            echo "処理済み: ${line}" >&"${output_fd}"
        else
            echo "エラー: ${line}" >&"${error_fd}"
        fi
    done
}

process_data
exec {input_fd}<&-
exec {output_fd}>&-
exec {error_fd}>&-

利点:

  • マジックナンバーではなく名前付きファイルディスクリプタ
  • 自動FD割り当てにより競合を回避
  • より読みやすく保守しやすいコード
  • オープンファイルハンドルの追跡が容易

配列の強化

連想配列の扱いの改善

複雑な配列操作のサポート強化:

# typeset で連想配列を宣言
declare -A config=(
    [host]="localhost"
    [port]="8080"
    [debug]="true"
)

# 強化された配列展開
for key in "${!config[@]}"; do
    printf '%s=%s\n' "${key}" "${config[${key}]}"
done

# 実用的な例: 設定パーサー
parse_config() {
    declare -gA app_config
    local line key value

    while IFS='=' read -r key value; do
        [[ "${key}" =~ ^[[:space:]]*# ]] && continue  # コメントをスキップ
        [[ -z "${key}" ]] && continue                  # 空行をスキップ

        # 空白をトリミング
        key="${key#"${key%%[![:space:]]*}"}"
        key="${key%"${key##*[![:space:]]}"}"
        value="${value#"${value%%[![:space:]]*}"}"
        value="${value%"${value##*[![:space:]]}"}"

        app_config["${key}"]="${value}"
    done < config.ini
}

多次元配列のサポート

入れ子になった配列構造の扱いが改善されました。

コード例

Readline 8.1 の統合

テキスト編集とコマンドライン操作の強化:

キーバインドと履歴

# ~/.inputrc での readline 設定
# 大文字小文字を区別しない補完を有効化
set completion-ignore-case on

# 補完候補の可視統計情報を有効化
set visible-stats on

# 曖昧な場合にすべての補完候補をすぐに表示
set show-all-if-ambiguous on

# 補完マッチングに色を使用
set colored-completion-prefix on

改善された履歴検索

# スクリプトまたは .bashrc 内で
# Ctrl+R で逆方向インクリメンタル検索(デフォルトですが、5.1 で強化)
bind '"\C-r": reverse-search-history'

# Ctrl+S で順方向インクリメンタル検索
bind '"\C-s": forward-search-history'

# 改善された履歴処理
shopt -s histappend           # 履歴に追記
shopt -s cmdhist              # 複数行コマンドを1エントリとして扱う
HISTCONTROL=ignoreboth        # 重複と先頭スペースを無視
HISTSIZE=10000
HISTFILESIZE=20000

シグナル処理の改善

サブシェルとプロセス置換におけるシグナル伝播の改善:

# サブシェルでのトラップ処理の強化
cleanup() {
    echo "クリーンアップ中..." >&2
    rm -f "${temp_file}"
    exit 130  # 128 + SIGINT
}

trap cleanup SIGINT SIGTERM

temp_file=$(mktemp)

# シグナルがパイプラインを通じて適切に伝播
long_running_task | process_output &
pid=$!

# 適切なシグナル処理でバックグラウンドジョブを待機
wait "${pid}" 2>/dev/null
exit_code=$?

if [[ ${exit_code} -gt 128 ]]; then
    signal=$((exit_code - 128))
    echo "プロセスがシグナル ${signal} で終了しました" >&2
fi

バグ修正とエッジケース

サブシェルの処理

サブシェル生成時の動作改善:

# より信頼性の高いサブシェル変数の継承
outer_var="親"

(
    # サブシェルは親の変数をより確実に継承
    echo "サブシェル内: ${outer_var}"
    inner_var="子"
)

# outer_var はまだアクセス可能、inner_var は不可
echo "サブシェル後: ${outer_var}"

パターンマッチングのエッジケース

グロブパターンマッチングのエッジケースを修正:

# 特殊文字を含む、より信頼性の高いグロブマッチング
shopt -s nullglob  # マッチしないグロブは空の展開に
shopt -s extglob   # 拡張パターンマッチング

# 例: ファイルをマッチングし、マッチしない場合は適切に処理
files=(*.txt)
if [[ ${#files[@]} -eq 0 ]]; then
    echo ".txt ファイルが見つかりません"
else
    printf '見つかりました: %s\n' "${files[@]}"
fi

パフォーマンスの改善

  • ループ内での変数展開の高速化
  • 配列操作の最適化
  • 大規模配列のメモリ使用量削減
  • パターンマッチングの効率改善

互換性に関する注意

Bash 5.0 からのアップグレード

ほとんどのスクリプトは互換性がありますが、以下の点に注意:

  • EPOCHSECONDS と EPOCHREALTIME は新しいため、古いバージョンを対象とする場合は存在確認を行う
  • SRANDOM はすべてのシステムで利用できるとは限らない
  • 展開動作の一部のマイナーなエッジケースが修正された

バージョンチェック

# Bash 5.1 の機能を使用する前にバージョンを確認
if [[ "${BASH_VERSINFO[0]}" -ge 5 ]] && [[ "${BASH_VERSINFO[1]}" -ge 1 ]]; then
    # Bash 5.1 の機能を安全に使用
    timestamp="${EPOCHSECONDS}"
else
    # 古いバージョンのフォールバック
    timestamp=$(date +%s)
fi

参考資料

追加リソース

より広範なBash開発パターンとベストプラクティスについては、以下を参照:

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-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-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.

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).

関連スキル