Community写作与编辑github.com

Jamie-BitFlight/bash-portability

编写可移植 POSIX 兼容脚本的指南,并了解何时利用 Bash 特有功能。

bash-portability 是什么?

该技能提供编写可移植、POSIX 兼容的 Shell 脚本的全面指南,同时帮助开发者识别何时可以安全地使用 Bash 特有功能。它涵盖了 Shebang 选择(`#!/usr/bin/env bash`、`#!/bin/sh`、`#!/bin/bash`)、POSIX 与 Bash 特性矩阵的详细对比(如 `[[ ]]`、数组、`local`、大小写转换等),并给出了实际的 POSIX 兼容模式示例,包括条件判断、大小写转换、子串操作和文件读取。此外,它还介绍了 Bash 特有功能(如扩展测试、数组、参数扩展、Here Strings、进程替换)以及 Shell 类型检测方法。该技能适用于任何需要编写或评估 Shell 脚本的 AI Agent 平台(如 Claude Code、Codex、Cursor),帮助开发者在兼容性和现代化 Bash 功能之间做出明智选择。根据其 SKILL.md 文档,该技能通过决策指南和常见可移植性陷阱,确保脚本在不同系统(bash、sh、dash、zsh)上都能正确运行。

兼容平台~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 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Bash 可移植性

编写可移植的 POSIX 兼容脚本指南,并了解何时利用 Bash 特有功能。

Shebang 选择

使用 #!/usr/bin/env bash 编写 Bash 脚本

#!/usr/bin/env bash

原因: 在 PATH 中搜索 bash,适用于 bash 可能位于不同位置的系统。

使用 #!/bin/sh 编写 POSIX 脚本

#!/bin/sh

原因: 当不需要 bash 功能时,提供最大可移植性。在许多系统上,/bin/sh 是 dash 或其他 POSIX shell。

需要时使用直接路径

#!/bin/bash

仅在以下情况使用: 系统要求保证 bash 位置,或安全策略要求绝对路径。

POSIX 与 Bash 特性矩阵

特性POSIXBash建议
[[ ]]否是在 POSIX 下使用 [ ]
(( ))否是在 POSIX 下使用 [ ] 配合 -eq 等
数组否是使用位置参数或文件
local部分是通常安全
${var,,}否4+在 POSIX 下使用 tr
<<<否是使用 echo | cmd
=~ 正则否是使用 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" : '.\(.{5}\)')  # 字符 4-8
substr=$(echo "$string" | cut -c4-8)

# 字符串长度
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 <<< "input string"

# POSIX 等效
var=$(echo "input string")

进程替换

# Bash - 比较两个命令输出
diff <(sort file1) <(sort file2)

# POSIX 等效(使用临时文件)
sort file1 > /tmp/sorted1
sort file2 > /tmp/sorted2
diff /tmp/sorted1 /tmp/sorted2

检测 Shell 类型

# 检查是否在 bash 中运行
if [ -n "${BASH_VERSION:-}" ]; then
    echo "正在 Bash 中运行"
fi

# 检查 bash 版本以支持特性
if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ]; then
    echo "Bash 4+ 可用"
fi

# 通用 shell 检测
case "${SHELL##*/}" in
    bash) echo "bash" ;;
    zsh)  echo "zsh" ;;
    *)    echo "other" ;;
esac

可移植工具函数

代码示例

可移植性决策指南

使用 POSIX 的情况:

  • 脚本在最小系统(容器、嵌入式)上运行
  • 目标包括 dash、ash 或 busybox sh
  • 需要最大兼容性
  • 脚本是系统初始化的一部分

使用 Bash 的情况:

  • 目标系统保证有 bash
  • 需要使用数组、关联数组或正则表达式
  • 需要复杂的字符串操作
  • 代码清晰度显著提高
  • 需要交互式功能

常见可移植性陷阱

echo vs printf

# 有问题 - 行为各异
echo -n "不换行"
echo -e "含有\t制表符"

# 可移植的
printf '%s' "不换行"
printf '含有\t制表符\n'

变量赋值

# 到处可用
var="value"

# 某些 shell 可能失败
var = "value"  # = 两侧有空格是错误的

导出与赋值结合

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

相关技能