Token导航 LogoToken导航TokenDH.com
开发规范执行命令github未标认证来源可访问clear审计通过

shell-best-practices外壳最佳实践

Agent Skill

shell-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,344

周安装

56

GitHub Stars

142

下载量

448
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:shell-best-practices(外壳最佳实践)
来源仓库:https://github.com/thebushidocollective/han
仓库路径:skills/shell-best-practices
安装命令:
npx skills add https://github.com/thebushidocollective/han --skill shell-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill shell-best-practices

简介

shell-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。

  • 它支持结合来源仓库、安装命令和原始 README 继续核验具体用法。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 可结合来源仓库、安装命令和原始 README 继续核验具体用法。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

SKILL.md

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 File

# Correct - preserves whitespace
while IFS= read -r line; do
    echo "$line"
done < "$filename"

# With process substitution
while IFS= read -r line; do
    echo "$line"
done < <(some_command)

Iterate with Index

files=("one.txt" "two.txt" "three.txt")

for i in "${!files[@]}"; do
    echo "Index $i: ${files[i]}"
done

Arrays

Declaration and Usage

# Indexed array
declare -a files=()
files+=("file1.txt")
files+=("file2.txt")

# Access all elements
for f in "${files[@]}"; do
    echo "$f"
done

# Array length
echo "${#files[@]}"

# Associative array (Bash 4+)
declare -A config
config[host]="localhost"
config[port]="8080"

echo "${config[host]}"

Array Best Practices

# Quote expansions
"${array[@]}"   # All elements, word-split
"${array[*]}"   # All elements, single string

# Check if empty
if [[ ${#array[@]} -eq 0 ]]; then
    echo "Empty array"
fi

# Check for key (associative)
if [[ -v config[key] ]]; then
    echo "Key exists"
fi

Command Execution

Check Command Existence

# Preferred method
if command -v docker &>/dev/null; then
    echo "Docker is installed"
fi

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

require_command git
require_command docker

Capture Output and Status

# Capture output
output=$(some_command)

# Capture output and status
if output=$(some_command 2>&1); then
    echo "Success: $output"
else
    echo "Failed: $output" >&2
fi

# Check status without output
if some_command &>/dev/null; then
    echo "Command succeeded"
fi

Safe Command Substitution

# Use $() not backticks
result=$(command)      # Good
result=`command`       # Avoid

# Nested substitution
result=$(echo $(date)) # Works with $()

Portability

POSIX vs Bash

FeaturePOSIXBash
Test syntax[][[]]
ArraysNoYes
$()YesYes
${var//pat/rep}NoYes
[[=~]] regexNoYes
(()) arithmeticNoYes

Portable Alternatives

# Instead of [[ ]], use [ ] with quotes
if [ -f "$file" ]; then
if [ "$str" = "value" ]; then

# Instead of (( )), use [ ] with -eq
if [ "$count" -gt 10 ]; then

# Instead of ${var//pat/rep}
echo "$var" | sed 's/pat/rep/g'

# Instead of arrays, use space-separated strings
files="one.txt two.txt three.txt"
for f in $files; do
    echo "$f"
done

Security

Avoid Eval

# Bad - code injection risk
eval "$user_input"

# Better - use arrays for command building
cmd=("grep" "-r" "$pattern" "$directory")
"${cmd[@]}"

Sanitize Inputs

# Validate expected format
if [[ ! "$input" =~ ^[a-zA-Z0-9_-]+$ ]]; then
    die "Invalid input format"
fi

# Escape for use in commands
escaped=$(printf '%q' "$input")

Temporary Files

# Secure temp file creation
temp_file=$(mktemp) || die "Failed to create temp file"
trap 'rm -f "$temp_file"' EXIT

# Secure temp directory
temp_dir=$(mktemp -d) || die "Failed to create temp dir"
trap 'rm -rf "$temp_dir"' EXIT

Logging

Basic Logging

readonly LOG_FILE="/var/log/myapp.log"

log() {
    local level="$1"
    shift
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a "$LOG_FILE"
}

log_info() { log "INFO" "$@"; }
log_warn() { log "WARN" "$@" >&2; }
log_error() { log "ERROR" "$@" >&2; }

# Usage
log_info "Starting process"
log_error "Failed to connect"

Verbose Mode

VERBOSE="${VERBOSE:-false}"

debug() {
    if [[ "$VERBOSE" == "true" ]]; then
        echo "DEBUG: $*" >&2
    fi
}

# Enable with: VERBOSE=true ./script.sh

Complete Script Template

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

# =============================================================================
# Script: example.sh
# Description: Template demonstrating shell best practices
# Usage: ./example.sh [options] <input_file>
# =============================================================================

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

# Exit codes
readonly EXIT_SUCCESS=0
readonly EXIT_FAILURE=1
readonly EXIT_INVALID_ARGS=2

# Logging functions
log_info() { echo "[INFO] $*"; }
log_error() { echo "[ERROR] $*" >&2; }

# Error handling
die() {
    log_error "$@"
    exit "$EXIT_FAILURE"
}

cleanup() {
    local exit_code=$?
    rm -f "${temp_file:-}"
    exit "$exit_code"
}
trap cleanup EXIT

# Argument parsing
usage() {
    cat <<EOF
Usage: $SCRIPT_NAME [options] <input_file>

Options:
    -h, --help      Show this help message
    -v, --verbose   Enable verbose output
    -o, --output    Output directory (default: ./output)

Examples:
    $SCRIPT_NAME input.txt
    $SCRIPT_NAME -v -o /tmp/output input.txt
EOF
}

parse_args() {
    local OPTIND opt
    while getopts ":hvo:-:" opt; do
        case "$opt" in
            h) usage; exit "$EXIT_SUCCESS" ;;
            v) VERBOSE=true ;;
            o) OUTPUT_DIR="$OPTARG" ;;
            -) case "$OPTARG" in
                   help) usage; exit "$EXIT_SUCCESS" ;;
                   verbose) VERBOSE=true ;;
                   output=*) OUTPUT_DIR="${OPTARG#*=}" ;;
                   *) die "Unknown option: --$OPTARG" ;;
               esac ;;
            :) die "Option -$OPTARG requires an argument" ;;
            \?) die "Unknown option: -$OPTARG" ;;
        esac
    done
    shift $((OPTIND - 1))

    if [[ $# -lt 1 ]]; then
        usage
        exit "$EXIT_INVALID_ARGS"
    fi

    INPUT_FILE="$1"
}

# Validate inputs
validate() {
    [[ -f "$INPUT_FILE" ]] || die "File not found: $INPUT_FILE"
    [[ -r "$INPUT_FILE" ]] || die "File not readable: $INPUT_FILE"
    mkdir -p "$OUTPUT_DIR" || die "Cannot create output directory"
}

# Main logic
main() {
    # Defaults
    VERBOSE="${VERBOSE:-false}"
    OUTPUT_DIR="${OUTPUT_DIR:-./output}"

    parse_args "$@"
    validate

    log_info "Processing $INPUT_FILE"
    # ... main logic here ...
    log_info "Done"
}

main "$@"

When to Use This Skill

  • Writing new shell scripts from scratch
  • Reviewing shell scripts for issues
  • Refactoring legacy shell code
  • Debugging script failures
  • Improving script security
  • Making scripts more portable
  • Setting up proper error handling

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

29.94%
按下载量换算134

OpenCode

23.44%
按下载量换算105

Codex

18.5%
按下载量换算83

Antigravity

13.59%
按下载量换算61

Cursor

8.24%
按下载量换算37

windsurf

3.56%
按下载量换算16

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/thebushidocollective/han --skill shell-best-practices;npx skills add thebushidocollective/han --skill "shell-best-practices" 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills