Communitygithub.com

Jamie-BitFlight/bash-53-features

Bash 5.3 版本的發布功能與改善,附有實用範例。適合在使用 Bash 5.3 功能、新的命令替換、GLOBSORT、可載入內建指令,或使用者詢問 Bash 5.3 變更、新功能、版本特定能力時使用。

bash-53-features 是什麼?

Bash 5.3 於 2025 年 7 月發布,引入了革命性的命令替換語法、新的變數、可載入內建指令,以及更佳的 C 標準符合性。此技能詳細介紹了 `${ command; }` 這種無需 fork 子行程的內部替換語法,能顯著提升迴圈與簡單指令的執行效能;以及 `${| command; }` 自動將輸出存入 `REPLY` 變數的簡潔方式。同時也涵蓋了 `GLOBSORT` 變數以控制檔名展開的排序順序、`compgen` 與 `read -E` 的增強、`source -p` 路徑指定、`printf` 的多位元組支援,以及 `kv`、`strptime`、`fltexpr` 等新可載入內建指令。該技能適用於所有支援 Bash 5.3 的環境,並提供豐富的程式碼範例與版本遷移指南,協助開發者快速掌握並採用這些新功能。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Jamie-BitFlight/claude_skills/tree/main/plugins/bash-development/skills/bash-53-features

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Bash 5.3 功能與改善

Bash 5.3 於 2025 年 7 月發布,引入了革命性的命令替換語法、新的變數、可載入內建指令,以及更佳的 C 標準符合性。

革命性的命令替換

高效的 shell 內部執行:${ command; }

不需建立子行程即可執行命令,大幅提升效能:

# 傳統命令替換(建立子 shell)
result=$(echo "Hello, World")

# 新的:Shell 內部命令替換(無 fork!)
# 注意:在開頭 '{' 之後必須有空格(或 tab/換行/|)
result=${ echo "Hello, World"; }

# 實用範例:快速變數指派
config_value=${ grep "^timeout=" config.txt | cut -d= -f2; }

# 效能比較函數
benchmark_substitution() {
    local i
    local start end

    echo "測試傳統替換..."
    start="${EPOCHREALTIME}"
    for ((i = 0; i < 1000; i++)); do
        result=$(echo "${i}")
    done
    end="${EPOCHREALTIME}"
    printf '傳統:%.4f 秒\n' \
        "$(awk "BEGIN {print ${end} - ${start}}")"

    echo "測試新的 shell 內部替換..."
    start="${EPOCHREALTIME}"
    for ((i = 0; i < 1000; i++)); do
        result=${ echo "${i}"; }
    done
    end="${EPOCHREALTIME}"
    printf 'Shell 內部:%.4f 秒\n' \
        "$(awk "BEGIN {print ${end} - ${start}}")"
}

benchmark_substitution

優點:

  • 無子行程建立負擔
  • 簡單指令執行更快速
  • 減少迴圈中的資源使用
  • 語法與命令替換相似

REPLY 變數捕捉:${| command; }

執行命令並自動將輸出存到 REPLY。注意:REPLY 是該替換的區域變數——其值會在完成後還原,因此必須立即捕捉:

程式碼範例

優點:

  • 更簡潔的程式碼,無需中間變數
  • 一致的捕捉機制
  • 減少視覺混亂
  • 非常適合快速原型開發

使用案例比較

# 字串操作 - 使用 shell 內部以獲得效率
filename="document.txt"
basename=${ echo "${filename%.*}"; }
extension=${ echo "${filename##*.}"; }

# 輸出捕捉 - 使用 REPLY 以提高清晰度
${| df -h / | tail -1 | awk '{print $5}'; }
disk_usage="${REPLY}"
echo "磁碟使用率:${disk_usage}"

# 複雜管道 - 傳統方式可能仍較清晰
result=$(cat file.txt | grep pattern | sort | uniq)

GLOBSORT 變數

控制檔名與路徑名稱展開的排序順序。指定符可選擇性地加上前綴 +(遞增,預設)或 -(遞減):

程式碼範例

可用的排序指定符:

  • name — 依檔名字母排序
  • size — 依檔案大小
  • mtime — 依修改時間
  • atime — 依存取時間
  • ctime — 依 inode 變更時間
  • blocks — 依分配的區塊數量
  • numeric — 依檔名開頭數字排序
  • nosort — 停用排序(glob 順序)
  • 前綴:+(遞增,預設)或 -(遞減)

增強的內建指令

compgen 搭配變數儲存

直接將補全結果存入變數:

程式碼範例

read 搭配 Readline 補全(-E)

互動式輸入並支援自動補全:

# 在 read 期間啟用 readline 補全
choose_file() {
    local file

    echo "請輸入檔名(按 Tab 補全):"
    read -e -r -E -p "> " file

    if [[ -f "${file}" ]]; then
        echo "已選取:${file}"
        return 0
    else
        echo "找不到檔案:${file}"
        return 1
    fi
}

choose_file

# 實用範例:互動式設定
configure_app() {
    local config_file

    echo "請選取設定檔:"
    read -e -r -E -p "設定檔:" config_file

    if [[ -f "${config_file}" ]]; then
        ${| grep -c "^[^#]" "${config_file}"; }
        local line_count="${REPLY}"
        echo "找到 ${line_count} 行有效設定"
    fi
}

source 搭配路徑(-p)

指定來源腳本的搜尋路徑:

程式碼範例

printf 增強

多位元組字串與表示法的選項:

# 增強的 printf 選項
printf '%q\n' "含有空白的字串"  # shell 引號輸出

# 新的:多位元組字串支援改善
text="Hello, 世界"
printf '長度:%d 位元組\n' "${#text}"

# 實用範例:安全指令建構
build_command() {
    local -a args=("$@")
    local arg cmd=""

    for arg in "${args[@]}"; do
        cmd+=$(printf '%q ' "${arg}")
    done

    echo "安全指令:${cmd}"
}

build_command ls "-l" "含有空白的檔案.txt"

新的可載入內建指令

kv - 鍵值陣列

從鍵值資料建立關聯式陣列。注意: kv 內建指令的存在已在 Bash 5.3 中確認;以下顯示的介面僅為示意——請在載入後用 help kv 驗證:

程式碼範例

strptime - 日期剖析

將文字日期剖析為 Unix 時間戳記。注意: strptime 內建指令的存在已在 Bash 5.3 中確認;以下顯示的介面僅為示意——請在載入後用 help strptime 驗證:

程式碼範例

fltexpr - 浮點數計算

無需外部工具即可進行浮點數運算:

程式碼範例

POSIX 模式改善

增強的 POSIX 相容性:

# 啟用 POSIX 模式
set -o posix

# 字串比較現在遵循地域規則
[[ "ä" < "z" ]]  # 依地域決定比較結果

# 內建指令更嚴格符合 POSIX
# test、trap、wait、bind 更嚴格符合標準

# 實用範例:可攜式腳本開頭
#!/usr/bin/env bash

if [[ "${BASH_VERSINFO[0]}" -ge 5 ]] && [[ "${BASH_VERSINFO[1]}" -ge 3 ]]; then
    # 可使用 Bash 5.3+,採用現代功能
    USE_MODERN_FEATURES=1
else
    # 為可攜性回到 POSIX 模式
    set -o posix
    USE_MODERN_FEATURES=0
fi

改善的錯誤回報

更詳細的錯誤訊息:

程式碼範例

C 標準符合性改善

Bash 5.3 改善對於現代 C 標準的符合性(編譯最低需求仍為 C90):

  • 不再支援 K&R C 編譯器
  • 程式碼庫現代化以符合標準
  • 更好的最佳化機會
  • 改善型別安全性

注意: 這主要影響從原始碼編譯 Bash 的開發者,而非一般使用者。

效能改善

  • 無需 fork 的命令替換(${ cmd; })大幅降低負擔
  • 透過 GLOBSORT 最佳化的 glob 展開
  • 更快的內建指令操作
  • 各種操作減少記憶體使用
# 效能基準:傳統 vs 新式替換
benchmark() {
    local iterations=10000
    local i start end

    start="${EPOCHREALTIME}"
    for ((i = 0; i < iterations; i++)); do
        result=$(echo test)
    done
    end="${EPOCHREALTIME}"
    printf '傳統:%.4f 秒\n' \
        "$(awk "BEGIN {print ${end} - ${start}}")"

    start="${EPOCHREALTIME}"
    for ((i = 0; i < iterations; i++)); do
        result=${ echo test; }
    done
    end="${EPOCHREALTIME}"
    printf 'Shell 內部:%.4f 秒\n' \
        "$(awk "BEGIN {print ${end} - ${start}}")"
}

benchmark

遷移指南

從 Bash 5.2 到 5.3

大部分腳本相容,但可考慮:

# 利用新的命令替換提升效能
# 舊方式:
for file in *; do
    size=$(stat -f%z "${file}" 2>/dev/null)
done

# 新方式(更快):
for file in *; do
    ${| stat -f%z "${file}" 2>/dev/null; }
    size="${REPLY}"
done

# 使用 GLOBSORT 改善檔案處理
GLOBSORT="-mtime"
for file in *.log; do
    process_recent_log "${file}"
done

# 在適當時利用新的內建指令
# 取代:awk 計算
# 使用:fltexpr 進行浮點數運算

版本偵測

# 檢查 Bash 5.3 功能
if [[ "${BASH_VERSINFO[0]}" -ge 5 ]] && [[ "${BASH_VERSINFO[1]}" -ge 3 ]]; then
    echo "Bash 5.3+ 功能可用"
    CAN_USE_INSITU_SUBSTITUTION=1
    CAN_USE_GLOBSORT=1
else
    echo "Bash 版本:${BASH_VERSION}"
    CAN_USE_INSITU_SUBSTITUTION=0
    CAN_USE_GLOBSORT=0
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-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-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).

相關技能