Bash Shell Scripting 标志

Bash Shell Scripting

社区
d-padmanabhan
bash-shell-scripting

Bash scripting best practices for production-grade scripts, CLI tools, and Makefiles. Covers strict mode, error handling, portability, performance patterns, and argument parsing. Use when working with .sh files, Makefiles, shell scripts, or when asking about Bash, shell scripting, CLI design, or command-line tools.

概览

发布者d-padmanabhan
代码仓库agent-engineering-handbook
技能名称bash-shell-scripting
星标数
20
复刻数
3
附带文件
7
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 7 个随附文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 d-padmanabhan 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Bash Shell Scripting AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/d-padmanabhan/agent-engineering-handbook/tree/main/skills/bash-shell-scripting
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/d-padmanabhan/agent-engineering-handbook.git /tmp/agent-engineering-handbook
mkdir -p .claude/skills
cp -r /tmp/agent-engineering-handbook/skills/bash-shell-scripting .claude/skills/bash-shell-scripting
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Bash Shell Scripting,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Bash Shell Scripting。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Bash Shell Scripting 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Bash & Shell Scripting

Mandatory gates are owned by the Bash rule (${HANDBOOK_ROOT}/rules/140-bash.mdc). This skill owns procedures and examples.

Core Principles

  • DRY: Don't Repeat Yourself
  • KISS: Keep It Simple
  • Fail Fast: Exit on errors immediately
  • Zero Warnings: Must pass shellcheck

Quick Reference

bash
set -euo pipefail           # Strict mode (fail-fast)
set -uo pipefail            # Controlled mode (explicit error handling)
set -Euo pipefail           # Strict + ERR trap propagation
command -v cmd >/dev/null   # Check if command exists (portable)
trap 'cleanup' EXIT         # Always cleanup
flock -n 200 || exit 1      # Prevent concurrent runs
readonly VAR="value"        # Immutable constant
local var="value"           # Function-local variable

Core Standards

AspectStandard
Shebang#!/usr/bin/env bash or #!/bin/bash
Safety Modeset -euo pipefail (strict) or set -uo pipefail (controlled)
LintingMust pass shellcheck with 0 errors/warnings
FormattingMust pass shfmt -i 2 -ci -sr -bn; prefer ~100-character lines
Extension.sh for scripts
VariablesUppercase constants/globals, lowercase locals, descriptive names, braces + quotes ("${VAR}")

Generation Contract

For any non-trivial script (more than 10-15 lines, more than one command phase, argument parsing, dependency checks, config resolution, build/deploy/verify steps), generate this structure:

  1. Header block.
  2. Commented debug toggle (# set -x), disabled by default.
  3. Strict or controlled mode.
  4. Readonly constants and timestamped LOGFILE.
  5. logmsg, die, and optional debug helper.
  6. require_command for dependencies.
  7. Helper functions with lowercase locals.
  8. parse_args.
  9. main().
  10. main "$@" as the final line.

Reject generated Bash that skips this structure unless the script is intentionally tiny and linear.

Error Handling Modes

Strict Mode (Fail-Fast)

bash
set -euo pipefail  # Exit immediately on any error

Use for: Simple linear scripts, dependency installation, straightforward validation.

Controlled Mode (Explicit)

bash
set -uo pipefail  # No -e: handle errors explicitly

Use for: Diagnostics, cleanup operations, commands where failure is expected.

Strict + ERR Trap

bash
set -Euo pipefail

trap 'echo "ERROR in ${FUNCNAME[0]:-main} at line $LINENO"' ERR

Use for: Production scripts with comprehensive error handling.

Script Template

bash
#!/usr/bin/env bash
#
# Script Name         : <script_name>.sh
#
# Purpose             : <One or two sentences explaining what the script does.
#                       Wrap continuation lines under the value column.>
#
# Dependencies        : <List required commands, or "None">
#
# Script Usage        : ./<script_name>.sh [options] <arguments>
#
#                       <Examples and argument notes.>
#
##----------------------------------------------------------------------------------------##
# Turn debug on or off
# set -x
##----------------------------------------------------------------------------------------##

set -euo pipefail

readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly DTTM="$(date -u +"%Y%m%d_%H%M%S")"
readonly SCRIPT_NAME="$(basename "${0}" .sh)"
readonly LOGFILE="${SCRIPT_NAME}_${DTTM}.log"

cleanup() {
  rm -f "${TEMP_FILE:-}" 2>/dev/null || true
}
trap cleanup EXIT

logmsg() {
  local timestamp
  timestamp="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  printf "%s: %s\n" "${timestamp}" "$*" | tee -a "${LOGFILE}" >&2
}

die() {
  logmsg "ERROR: $*"
  exit 1
}

debug() {
  [[ "${DEBUG:-0}" == "1" ]] && logmsg "DEBUG: $*"
}

require_command() {
  local command_name="$1"
  command -v "${command_name}" >/dev/null 2>&1 || die "Missing command: ${command_name}"
}

main() {
  local arg="${1:-}"
  [[ -z "${arg}" ]] && die "Usage: ${SCRIPT_NAME} <argument>"

  require_command jq
  logmsg "Processing: ${arg}"
  # Main logic here
}

main "$@"

Minimal dependency helper:

bash
require_command() {
  local command_name="$1"
  command -v "${command_name}" >/dev/null 2>&1 || die "Missing command: ${command_name}"
}

Best Practices

Always Quote Variables

bash
# ✅ GOOD
echo "${var}"
[[ -n "${var:-}" ]] && echo "set"
printf "%s\n" "${array[@]}"

# ❌ BAD
echo $var
[ -n $var ] && echo "set"

Process Text and JSON Deliberately

bash
# Simple string changes: prefer Bash parameter expansion
normalized_path="${input_path//\/\//\/}"

# Line/column text processing: awk/sed are appropriate when necessary
awk -F',' 'NR > 1 && $3 == "active" { print $1 }' users.csv
sed -E 's/[[:space:]]+$//' input.txt > output.txt

# JSON: use jq; never parse JSON with grep/sed/string splitting
jq -e '.users[] | select(.active == true) | .id' users.json

Terminal-safe ANSI Colors

Define color codes only when writing to an interactive terminal. Do not emit ANSI escapes into log files, CI summaries, or non-terminal output.

bash
if [[ -t 2 ]]; then
  readonly RED=$'\033[0;31m'
  readonly GREEN=$'\033[0;32m'
  readonly YELLOW=$'\033[1;33m'
  readonly NC=$'\033[0m'
else
  readonly RED=''
  readonly GREEN=''
  readonly YELLOW=''
  readonly NC=''
fi

if [[ -n "${GREEN}" ]]; then
  printf "%sStarting job%s\n" "${GREEN}" "${NC}" >&2
fi
logmsg "Starting job"

if [[ -n "${RED}" ]]; then
  printf "%sInvalid input%s\n" "${RED}" "${NC}" >&2
fi
logmsg "Invalid input"

Use Functions

bash
process_file() {
    local file="$1"
    [[ -f "$file" ]] || return 1
    # Process file
}

Know When Bash Is the Wrong Tool

Use Bash for glue: calling CLIs, moving files, simple validation, CI wrappers, and deployment orchestration. Prefer Python/Go/Node when the script needs complex data structures, non-trivial JSON transformation, API clients with pagination/retry state, concurrency, long-lived daemons, or more than a few hundred lines of business logic.

Use main() When the Script Has Phases

Tiny one-shot scripts can stay linear, but once a script has multiple named phases, wrap execution in main(). This separates globals/functions from execution, makes the script read like a table of contents, and makes future testing/refactoring easier.

bash
main() {
  parse_args "$@"
  require_command curl
  require_command git
  require_command npm
  resolve_env_file
  install_dependencies_if_needed
  build_assets
  load_deploy_environment
  deploy_worker_assets "$@"
  verify_worker_hostnames
}

main "$@"

Check Command Existence

bash
command -v docker >/dev/null 2>&1 || die "docker is required"

Temporary Files

bash
readonly TEMP_FILE="$(mktemp)"
trap 'rm -f "$TEMP_FILE"' EXIT

echo "data" > "$TEMP_FILE"

Lock Files

bash
exec 200>"/tmp/${SCRIPT_NAME}.lock"
flock -n 200 || { echo "Already running"; exit 1; }

Performance Patterns

Avoid Subshells in Loops

bash
# ❌ BAD - subshell, variables don't persist
count=0
cat file.txt | while read -r line; do
    count=$((count + 1))
done
echo "$count"  # Empty! (subshell issue)

# ✅ GOOD - process substitution
count=0
while read -r line; do
    count=$((count + 1))
done < file.txt
echo "$count"  # Correct

Use Arrays

bash
# Arrays for multiple values
files=("file1.txt" "file2.txt" "file3.txt")
for file in "${files[@]}"; do
    process "$file"
done

# Append to array
files+=("file4.txt")

Argument Parsing

bash
show_help() {
    cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS] <file>

Options:
    -h, --help      Show this help
    -v, --verbose   Enable verbose mode
    -o, --output    Output file (default: stdout)
EOF
}

parse_args() {
    VERBOSE=false
    OUTPUT=""

    while [[ $# -gt 0 ]]; do
        case "$1" in
            -h|--help) show_help; exit 0 ;;
            -v|--verbose) VERBOSE=true; shift ;;
            -o|--output) OUTPUT="$2"; shift 2 ;;
            -*) die "Unknown option: $1" ;;
            *) break ;;
        esac
    done

    [[ $# -eq 0 ]] && die "Missing required argument"
    INPUT_FILE="$1"
}

Detailed References

  • Shell Utilities: See shell utilities (${HANDBOOK_ROOT}/skills/bash-shell-scripting/references/shell-utilities.md) for curl, jq, lynx
  • Makefile Patterns: See Makefile patterns (${HANDBOOK_ROOT}/skills/bash-shell-scripting/references/makefile-patterns.md)
  • CLI Design: See CLI design (${HANDBOOK_ROOT}/skills/bash-shell-scripting/references/cli-design.md)
  • Justfile Patterns: See Justfile patterns (${HANDBOOK_ROOT}/skills/bash-shell-scripting/references/justfile.md)
  • Repo Sync (rsync): See rsync repository synchronization (${HANDBOOK_ROOT}/skills/bash-shell-scripting/references/rsync-repo-sync.md)

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Bash Shell Scripting AI 技能有什么作用?

Bash scripting best practices for production-grade scripts, CLI tools, and Makefiles. Covers strict mode, error handling, portability, performance patterns, and argument parsing. Use when working with .sh files, Makefiles, shell scripts, or when asking about Bash, shell scripting, CLI design, or command-line tools.

为什么在 TypingMind 中使用 Bash Shell Scripting?

因为您只需安装一次,就能搭配任何模型使用。Bash Shell Scripting 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Bash Shell Scripting?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/d-padmanabhan/agent-engineering-handbook/tree/main/skills/bash-shell-scripting。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Bash Shell Scripting?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Bash Shell Scripting 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Bash Shell Scripting 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Bash Shell Scripting AI 技能免费吗?

是的。该技能源自 d-padmanabhan 在 GitHub 上以 MIT 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇