Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

shell-scripting

БесплатноБез исполняемых скриптовНе проверен

Practical bash scripting guidance emphasising defensive programming, ShellCheck compliance, and simplicity. Use when writing shell scripts that need to be…

sammcjот sammcj★ 175 звёзд на GitHub

Об этом скилле

Bash Scripting Best Practices

Guidance for writing reliable, maintainable bash scripts following modern best practices. Emphasises simplicity, automated tooling, and defensive programming without over-engineering.

When to Use Shell (and When Not To)

Use Shell For:

  • Small utilities and simple wrapper scripts (<100 lines)
  • Orchestrating other programmes and tools
  • Simple automation tasks
  • Build/deployment scripts with straightforward logic
  • Quick data transformation pipelines

Do NOT Use Shell For:

  • Complex business logic or data structures
  • Performance-critical code
  • Scripts requiring extensive error handling
  • Anything over ~100 lines or with non-straightforward control flow
  • When you need proper data structures beyond arrays

If a script passes ~100 lines or gets complex, offer to rewrite it in Python or Go before it becomes unmaintainable.

Mandatory Foundations

Every bash script must have these elements:

1. Proper Shebang

#!/usr/bin/env bash

Why: Portable across systems where bash may not be at /bin/bash (e.g., macOS, BSD, NixOS).

Alternative: #!/bin/bash if you know the script only runs on Linux and prefer explicit paths.

2. Strict Mode

set -euo pipefail

What each flag does:

  • -e: Exit immediately if any command fails (non-zero exit)
  • -u: Treat unset variables as errors
  • -o pipefail: Pipe fails if ANY command in pipeline fails (not just the last)

When to add -x: Only for debugging, not in production scripts (makes output noisy).

3. ShellCheck Compliance

Run ShellCheck on EVERY script before committing:

shellcheck script.sh

Fix all warnings. ShellCheck catches:

  • Unquoted variables
  • Deprecated syntax
  • Common bugs and pitfalls
  • Portability issues

4. Basic Script Structure

#!/usr/bin/env bash
set -euo pipefail

# Brief description of what this script does

# Simple error reporting
die() {
    echo "Error: ${1}" >&2
    exit 1
}

# Your code here

Core Safety Patterns

Always Quote Variables

Why: Prevents word splitting and globbing disasters.

# Wrong - dangerous
cp $source $destination
rm -rf $prefix/bin

# Correct - safe
cp "${source}" "${destination}"
rm -rf "${prefix}/bin"

# Special case: Always use braces with variables
echo "${var}"      # Good
echo "$var"        # Acceptable but less consistent
echo $var          # Bad - unquoted

Check Required Variables

# Fail fast if required variables aren't set
: "${REQUIRED_VAR:?REQUIRED_VAR must be set}"

# Or with custom message
: "${DATABASE_URL:?DATABASE_URL is required. Set it in .env}"

Validate Inputs

# Check file exists before operating on it
-f &quot;${config_file}&quot; || die "Config file not found: ${config_file}"

# Check command exists before using it
command -v jq >/dev/null 2>&1 || die "jq is required but not installed"

# Validate directory before cd
-d &quot;${target_dir}&quot; || die "Directory does not exist: ${target_dir}"

Essential Patterns

Pattern 1: Simple Script Template

Use this for straightforward scripts:

#!/usr/bin/env bash
set -euo pipefail

# Description: Process log files and extract errors

die() {
    echo "Error: ${1}" >&2
    exit 1
}

# Check dependencies
command -v jq >/dev/null 2>&1 || die "jq required"

# Validate arguments
$# -eq 1 || die "Usage: ${0} <logfile>"
logfile="${1}"
-f &quot;${logfile}&quot; || die "File not found: ${logfile}"

# Main logic
grep ERROR "${logfile}" | jq -r '.message'

Pattern 2: Cleanup on Exit

Use trap for guaranteed cleanup:

#!/usr/bin/env bash
set -euo pipefail

# Create temp directory and ensure cleanup
tmpdir=$(mktemp -d)
trap 'rm -rf "${tmpdir}"' EXIT

# Now use tmpdir safely - cleanup happens automatically
echo "Working in: ${tmpdir}"

Pattern 3: Safe Function Definition

Functions should be simple and focused:

# Good: Simple, single-purpose function
check_dependency() {
    local cmd="${1}"
    command -v "${cmd}" >/dev/null 2>&1 || die "${cmd} not installed"
}

# Good: Local variables, clear purpose
process_file() {
    local file="${1}"
    local output="${2}"

    -f &quot;${file}&quot; || die "Input file missing: ${file}"

    # Do processing
    sed 's/foo/bar/g' "${file}" > "${output}"
}

Important: Declare and set variables from command substitution separately to catch errors:

# Wrong - hides errors
local result="$(failing_command)"

# Correct - catches errors
local result
result="$(failing_command)"  # Will fail properly with set -e

Pattern 4: Safe Array Handling

Arrays are useful for handling lists with spaces:

# Create array
declare -a files=("file one.txt" "file two.txt" "file three.txt")

# Iterate safely - always quote with [@]
for file in "${files[@]}"; do
    echo "Processing: ${file}"
done

# Build command arguments safely
declare -a flags=(--verbose --output "${output_file}")
mycommand "${flags[@]}" "${input}
Полный SKILL.md на GitHub

Установить shell-scripting в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл shell-scripting?

Practical bash scripting guidance emphasising defensive programming, ShellCheck compliance, and simplicity. Use when writing shell scripts that need to be reliable and maintainable.

Как установить скилл shell-scripting?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл shell-scripting запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить shell-scripting с