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ファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 7個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    d-padmanabhanがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルBash Shell ScriptingをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

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

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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を有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にBash Shell Scriptingを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Bash Shell Scriptingは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じ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)

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「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.

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を読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Bash Shell Scriptingを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Bash Shell Scriptingは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもBash Shell Scriptingを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Bash Shell Scripting」は無料ですか?

はい。d-padmanabhanがGitHubでMITライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇