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月发布)中新特性的全面指南,包括革命性的无需fork的 shell 内命令替换语法(`${ command; }`)和自动存储输出到 REPLY 变量的 `${| command; }` 语法,显著提升了脚本性能。它介绍了 `GLOBSORT` 变量,用于控制文件名扩展的排序顺序,并详细说明了 `compgen`、`read`、`source` 和 `printf` 等内置命令的增强功能,例如 `read` 的 readline 补全支持。此外,技能还涵盖了新的可加载内置命令(如 `kv`、`strptime`、`fltexpr`),并提供了 POSIX 模式改进、错误报告优化、C 标准兼容性提升以及从 Bash 5.2 迁移到 5.3 的实用指南。该技能主要以 Claude Code 为平台,通过丰富的代码示例帮助开发者快速掌握并应用这些新特性。

兼容平台✓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; }

无需 fork 即可执行命令,显著提升性能:

# 传统命令替换(创建子 Shell)
result=$(echo "Hello, World")

# 新:Shell 内命令替换(无 fork!)
# 注意:在 '{' 之后需要有一个空格(或制表符/换行符/|)
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)

为 source 脚本指定搜索路径:

代码示例

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 优化 globbing
  • 更快的内置操作
  • 各种操作中减少内存使用
# 基准测试:传统替换 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).

相关技能