mcpField
B
bash

bash

github.com/dralgorhythm開発12862 回インストール14 週間前に更新
リポジトリ

bash について

開発者向けのBashスクリプトリファレンスです。安全なスクリプト、変数、制御フロー、関数、エラー処理の再利用可能なパターンを紹介します。

主な機能

  1. 01スクリプトテンプレートと安全設定
  2. 02変数とデフォルト値のパターン
  3. 03ファイル・文字列の条件判定
  4. 04関数とログ記録
  5. 05クリーンアップトラップとエラー処理

活用シーン

  1. 01Bashスクリプトの書き始め
  2. 02失敗時の処理と後片付け
  3. 03より安全なシェル条件文の作成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/dralgorhythm/claude-agentic-framework --skill bash

インストール後、Claude Code で/bashを入力して読み込まれたか確認します。

詳細

Bash スクリプト

スクリプトテンプレート

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

# Script description
# Usage: ./script.sh <arg1> <arg2>

readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

main() {
    local arg1="${1:-default}"

    # Script logic here
    echo "Running with: $arg1"
}

main "$@"

安全設定

set -e          # Exit on error
set -u          # Error on undefined variables
set -o pipefail # Catch pipe failures
set -x          # Debug: print commands

変数

# Declaration
readonly CONST="immutable"
local var="function scoped"

# Default values
name="${1:-default}"      # Use default if unset
name="${1:?Error: missing}"  # Error if unset

# String operations
"${var^^}"    # Uppercase
"${var,,}"    # Lowercase
"${var#prefix}"  # Remove prefix
"${var%suffix}"  # Remove suffix

条件分岐

# File tests
[[ -f "$file" ]]  # Is file
[[ -d "$dir" ]]   # Is directory
[[ -r "$file" ]]  # Is readable
[[ -x "$file" ]]  # Is executable

# String tests
[[ -z "$var" ]]   # Is empty
[[ -n "$var" ]]   # Is not empty
[[ "$a" == "$b" ]] # Equals

# Numeric tests
(( num > 5 ))     # Greater than
(( num == 5 ))    # Equals

関数

log() {
    local level="$1"
    local message="$2"
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $message" >&2
}

die() {
    log "ERROR" "$1"
    exit 1
}

require_command() {
    command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
}

エラー処理

# Trap for cleanup
cleanup() {
    rm -rf "$TMP_DIR"
}
trap cleanup EXIT

# Catch errors
if ! result=$(some_command 2>&1); then
    die "Command failed: $result"
fi

ループ

# For loop
for item in "${array[@]}"; do
    echo "$item"
done

# While read
while IFS= read -r line; do
    echo "$line"
done < file.txt

# Process substitution
while read -r line; do
    echo "$line"
done < <(command)

ベストプラクティス

  1. すべての変数を引用符で囲みます:"$var"
  2. [ の代わりに [[ を使用します
  3. 関数内では local を使用します
  4. 定数には readonly を使用します
  5. 必ず set -euo pipefail を使用します
  6. lint には shellcheck を使用します

コメント