Posix shell scripting

From findscripter/everything-skills · View interactive version

Posix shell scripting is an AI agent skill from the GitHub repository findscripter/everything-skills. 当需要编写在 dash/ash/BusyBox/bash --posix 等任意 POSIX shell 上可移植运行的脚本时使用;做严格 POSIX sh 脚本的编写、bashism 排查与跨平台校验,产出 #!/bin/sh 脚本与 shellcheck -s sh 通过项;不适用于依赖 bash 专属特性(数组、[[、local、pipefail)或仅单机一次性命令;触发词:POSIX、dash、bashism、可移植脚本

How to use this skill

Skill file

何时使用

步骤

  1. 定目标与约束:确认目标 shell(至少含 dash + BusyBox ash)、目标平台、必需输入与退出码语义。
  2. 写脚本骨架:#!/bin/sh + set -eu(POSIX 无 pipefail)+ 用法函数 + -h 帮助。
  3. 遵守 POSIX 约束(见下「指令」),全程引用变量、[ ] 测试、printf 输出、$() 替换。
  4. 加安全/清理:trap 清理临时文件、umask 077、-- 终止选项、输入校验。
  5. 静态校验:shellcheck -s sh script.sh && shfmt -ln posix -d script.sh && checkbashisms script.sh && sh -n script.sh。
  6. 多 shell 实跑:在 dash、BusyBox ash、bash --posix(必要时 yash)上各跑一遍,容器化复现(alpine:latest=ash、debian:stable=dash)。

指令

核心约束(POSIX sh 没有的东西,碰到即改)

做法清单

示例

安全临时文件 + 清理 trap:

#!/bin/sh
set -eu
tmpfile=$(mktemp) || exit 1
trap 'rm -f "$tmpfile"' EXIT INT TERM

无数组——位置参数模拟数组:

set -- item1 item2 item3
for arg; do process "$arg"; done

分隔字符串拆分(用完还原 IFS):

items="a:b:c"
IFS=:; set -- $items; IFS=' '

逐行读文件(避免 for i in $(cat) 的子shell与分词陷阱):

while IFS=: read -r user pass uid gid; do
  printf '%s\n' "$user"
done < /etc/passwd

可移植条件与默认值:

[ -e "$file" ] || exit 1          # 存在性,全平台可用
value=${var:-default}             # var 未设/为空时取默认

引号 here-doc 阻止变量展开:cat <<'EOF' ... EOF。

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT 许可)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.