shell-best-practices
БесплатноБез исполняемых скриптовНе проверенUse when writing shell scripts following modern best practices. Covers portable scripting, Bash patterns, error handling, and secure coding.
от 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 "$config_file" || 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 "$input_file" || die "File not found: $input_file"
-r "$input_file" || 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 "$log_file" || 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 "$file"; then
if "$string" == "value"; 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 "$count" -gt 10; then
String Comparisons
# Equality
if "$str" == "value"; then
# Pattern matching
if "$str" == *.txt; then
# Regex matching
if [[ "$str" =~ ^[a-z]+$ ]]; then
# Empty/non-empty
if -z "$str"; then # empty
if -n "$str"; then # non-empty
Loops
Iterate Over Files
# Good - handles spaces in filenames
for file in *.txt; do
-e "$file" || 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
Установить shell-best-practices в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBashGrepGlobFAQ
Что делает скилл 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), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic