Command Palette

Search for a command to run...

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

shell-best-practices

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

Use when writing shell scripts following modern best practices. Covers portable scripting, Bash patterns, error handling, and secure coding.

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

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

Shell Scripting Best Practices

Comprehensive guide to writing robust, maintainable, and secure shell scripts following modern best practices.

Script Foundation

Shebang Selection

Choose the appropriate shebang for your needs:

# Portable bash (recommended)
#!/usr/bin/env bash

# Direct bash path (faster, less portable)
#!/bin/bash

# POSIX-compliant shell (most portable)
#!/bin/sh

# Specific shell version
#!/usr/bin/env bash
# Requires Bash 4.0+

Strict Mode

Always enable strict error handling:

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

# What these do:
# -e: Exit immediately on command failure
# -u: Treat unset variables as errors
# -o pipefail: Pipeline fails if any command fails

For debugging, add:

set -x  # Print commands as they execute

Script Header Template

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

# Script: script-name.sh
# Description: Brief description of what this script does
# Usage: ./script-name.sh [options] <arguments>

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

Variable Handling

Always Quote Variables

Prevents word splitting and glob expansion:

# Good
echo "$variable"
cp "$source" "$destination"
if [ -f "$file" ]; then

# Bad - can break on spaces/special chars
echo $variable
cp $source $destination
if [ -f $file ]; then

Use Meaningful Names

# Good
readonly config_file="/etc/app/config.yml"
local user_input="$1"
declare -a log_files=()

# Bad
readonly f="/etc/app/config.yml"
local x="$1"
declare -a arr=()

Default Values

# Use default if unset
name="${NAME:-default_value}"

# Use default if unset or empty
name="${NAME:-}"

# Assign default if unset
: "${NAME:=default_value}"

# Error if unset (with message)
: "${REQUIRED_VAR:?Error: REQUIRED_VAR must be set}"

Readonly and Local

# Constants
readonly MAX_RETRIES=3
readonly CONFIG_DIR="/etc/myapp"

# Function-local variables
my_function() {
    local input="$1"
    local result=""
    # ...
}

Error Handling

Exit Codes

Use meaningful exit codes:

# Standard codes
readonly EXIT_SUCCESS=0
readonly EXIT_FAILURE=1
readonly EXIT_INVALID_ARGS=2
readonly EXIT_NOT_FOUND=3

# Exit with code
exit "$EXIT_FAILURE"

Trap for Cleanup

cleanup() {
    local exit_code=$?
    # Clean up temporary files
    rm -f "${temp_file:-}"
    # Restore state if needed
    exit "$exit_code"
}

trap cleanup EXIT

# Script continues...
temp_file=$(mktemp)

Error Messages

error() {
    echo "ERROR: $*" >&2
}

warn() {
    echo "WARNING: $*" >&2
}

die() {
    error "$@"
    exit 1
}

# Usage
-f &quot;$config_file&quot; || die "Config file not found: $config_file"

Validate Inputs

validate_args() {
    if $# -lt 1; then
        die "Usage: $SCRIPT_NAME <input_file>"
    fi

    local input_file="$1"
    -f &quot;$input_file&quot; || die "File not found: $input_file"
    -r &quot;$input_file&quot; || die "File not readable: $input_file"
}

Functions

Function Definition

# Document functions
# Process a log file and extract errors
# Arguments:
#   $1 - Path to log file
#   $2 - Output directory (optional, default: ./output)
# Returns:
#   0 on success, 1 on failure
process_log() {
    local log_file="$1"
    local output_dir="${2:-./output}"

    -f &quot;$log_file&quot; || return 1

    grep -i "error" "$log_file" > "$output_dir/errors.log"
}

Return Values

# Return status
is_valid() {
    [[ -n "$1" && "$1" =~ ^[0-9]+$ ]]
}

if is_valid "$input"; then
    echo "Valid"
fi

# Capture output
get_config_value() {
    local key="$1"
    grep "^${key}=" "$config_file" | cut -d= -f2
}

value=$(get_config_value "database_host")

Conditionals

Use for Tests

# Good -  is more powerful and safer
if -f &quot;$file&quot;; then
if &quot;$string&quot; == &quot;value&quot;; then
if [[ "$string" =~ ^[0-9]+$ ]]; then

# Avoid - [ ] has limitations
if [ -f "$file" ]; then
if [ "$string" = "value" ]; then

Numeric Comparisons

# Use (( )) for arithmetic
if (( count > 10 )); then
if (( a == b )); then
if (( x >= 0 && x <= 100 )); then

# Or -eq/-lt/-gt in 
if &quot;$count&quot; -gt 10; then

String Comparisons

# Equality
if &quot;$str&quot; == &quot;value&quot;; then

# Pattern matching
if &quot;$str&quot; == *.txt; then

# Regex matching
if [[ "$str" =~ ^[a-z]+$ ]]; then

# Empty/non-empty
if -z &quot;$str&quot;; then  # empty
if -n &quot;$str&quot;; then  # non-empty

Loops

Iterate Over Files

# Good - handles spaces in filenames
for file in *.txt; do
    -e &quot;$file&quot; || continue  # Skip if no matches
    process "$file"
done

# With find for recursive
while IFS= read -r -d '' file; do
    process "$file"
done < <(find . -name "*.txt" -print0)

# Bad - breaks on spaces
for file in $(ls *.txt); do  # Don't do this

Read Lines from

Полный SKILL.md на GitHub

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

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

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

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

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

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

Read
Write
Edit
Bash
Grep
Glob

FAQ

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

Use when writing shell scripts following modern best practices. Covers portable scripting, Bash patterns, error handling, and secure coding.

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

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

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

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

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

Сравнить shell-best-practices с