Bash Scripting

作者 mindrally97184105b5da無授權條款269 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫5 週前更新

Bash scripting guidelines covering security, portability, error handling, and automation best practices for DevOps.

AI 產生的概覽

提供撰寫安全、可攜、易維護 Bash 指令碼的指引,適用於自動化與 DevOps 工作。

功能
提供一套 Bash 指令碼撰寫指引,涵蓋命名與結構、輸入驗證與安全性、程式碼品質、錯誤處理與清理,以及自動化實務。內容包含建議模式,例如嚴格錯誤處理、用於清理的 trap 與模組化函式,並附有一段簡短的範例指令碼骨架。它產出的是指引內容,而非可執行的指令碼。
適用情境
適用於撰寫、審查或統一用於自動化、環境佈建、備份或部署的 Bash 指令碼。適合重視可攜性、輸入驗證與可靠錯誤處理的情境。
執行需求
此技能不隨附指令碼或資源,僅為說明性指引。套用其建議時可能涉及 shellcheck 等工具,但閱讀這些指引除代理本身外無需其他條件。

Bash Scripting

You are an expert in Bash scripting with deep knowledge of shell programming, automation, and DevOps practices.

Core Principles

  • Write portable, maintainable scripts
  • Prioritize security and input validation
  • Use proper error handling throughout
  • Follow consistent naming and formatting

Naming & Structure

  • Use descriptive names for scripts and variables (e.g., backup_files.sh, log_rotation)
  • Employ modular scripts with functions to enhance readability and facilitate reuse
  • Include comments for each major section or function
  • Use lowercase with underscores for variable names

Input Validation & Security

  • Validate all inputs using getopts or manual validation logic
  • Avoid hardcoding; use environment variables or parameterized inputs
  • Apply the principle of least privilege in access and permissions
  • Quote all variable expansions to prevent word splitting
  • Sanitize user input before use

Code Quality

  • Ensure portability by using POSIX-compliant syntax
  • Use shellcheck to lint scripts and improve quality
  • Redirect output to log files where appropriate, separating stdout and stderr
  • Use meaningful exit codes

Error Handling & Cleanup

  • Use trap for error handling and cleaning up temporary files
  • Implement set -euo pipefail for strict error handling
  • Check command return codes explicitly when needed
  • Provide informative error messages

Best Practices

bash
#!/usr/bin/env bashset -euo pipefail
# Trap for cleanuptrap cleanup EXIT
cleanup() {    # Clean up temporary files    rm -f "${TEMP_FILE:-}"}
# Use functions for modularitymain() {    validate_input "$@"    process_data}
validate_input() {    [[ $# -lt 1 ]] && { echo "Usage: $0 <arg>"; exit 1; }}
main "$@"

Automation Best Practices

  • Automate cron jobs securely with proper authentication
  • Use SCP/SFTP for remote transfers with key-based authentication
  • Implement proper logging for auditing
  • Use lock files to prevent concurrent execution

Specific Use Cases

  • Automate VM or container provisioning
  • Bootstrap servers and configure environments
  • Manage backups with reliable, auditable processes
  • Implement deployment scripts with rollback capability

來源與署名

來源:mindrally/skills位於bash-scripting提交9718410

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架