mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+406
-271
@@ -1,292 +1,427 @@
|
||||
---
|
||||
description: This rule enforces best practices and coding standards for Bash scripting to improve code quality, maintainability, and security. It covers naming conventions, formatting, error handling, security, and performance considerations.
|
||||
globs: *.sh
|
||||
description: Enforces modern, robust, and maintainable bash scripting practices, focusing on error handling, quoting, variable management, and code organization.
|
||||
globs: **/*
|
||||
---
|
||||
# Bash Best Practices and Coding Standards
|
||||
# bash Best Practices
|
||||
|
||||
This document outlines the best practices and coding standards for writing Bash scripts. Following these guidelines will lead to more maintainable, readable, and robust code.
|
||||
This guide outlines the definitive best practices for writing bash scripts. Adhere to these rules to ensure your scripts are reliable, readable, and maintainable by the entire team.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure Best Practices
|
||||
### 1.1 Shebang and Interpreter Options
|
||||
Always start scripts with `#!/usr/bin/env bash` for portability. Immediately follow with `set -euo pipefail` to ensure robust error handling.
|
||||
|
||||
For large Bash projects, a well-defined directory structure is crucial. Consider the following structure:
|
||||
* `set -e` (errexit): Exit immediately if a command exits with a non-zero status.
|
||||
* `set -u` (nounset): Treat unset variables as an error and exit immediately.
|
||||
* `set -o pipefail`: The return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if all commands exit successfully.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Missing error handling
|
||||
```
|
||||
|
||||
project_root/
|
||||
├── bin/ # Executable scripts (main entry points)
|
||||
├── lib/ # Library scripts (reusable functions and modules)
|
||||
├── config/ # Configuration files (e.g., settings, environment variables)
|
||||
├── data/ # Data files (e.g., CSV, JSON)
|
||||
├── log/ # Log files generated by scripts
|
||||
├── tmp/ # Temporary files used during script execution
|
||||
├── tests/ # Unit and integration tests
|
||||
├── docs/ # Documentation (e.g., README, design documents)
|
||||
└── README.md # Project README
|
||||
✅ GOOD:
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Script logic here
|
||||
```
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
### 1.2 File Header and Comments
|
||||
Every script must begin with a descriptive header. Use clear, concise comments for functions and complex logic.
|
||||
|
||||
* **Executable Scripts:** Use descriptive names without extensions (e.g., `process_data`, `backup_system`).
|
||||
* **Library Scripts:** Use `.sh` extension (e.g., `string_utils.sh`, `database_functions.sh`). For bash-specific code use `.bash`.
|
||||
* **Configuration Files:** Use `.conf` or `.cfg` extensions (e.g., `app.conf`, `settings.cfg`).
|
||||
* **Test Files:** Use `_test.sh` suffix (e.g., `string_utils_test.sh`).
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
### 1.3. Module Organization
|
||||
## my-script.sh
|
||||
#
|
||||
# Description: This script performs a critical system backup.
|
||||
# It backs up configuration files and database dumps to a remote server.
|
||||
#
|
||||
# Usage: ./my-script.sh [--full | --incremental]
|
||||
#
|
||||
# Globals:
|
||||
# BACKUP_DIR
|
||||
# REMOTE_HOST
|
||||
#
|
||||
# Arguments:
|
||||
# --full: Perform a full backup.
|
||||
# --incremental: Perform an incremental backup.
|
||||
#
|
||||
# Returns:
|
||||
# 0 on success, non-zero on error.
|
||||
#
|
||||
# Author: Your Name <your.email@example.com>
|
||||
# Date: 2025-01-01
|
||||
#
|
||||
###############################################################################
|
||||
|
||||
* **Separate Concerns:** Divide your code into logical modules, each responsible for a specific task (e.g., database interaction, string manipulation, system monitoring).
|
||||
* **Reusable Functions:** Place reusable functions in library scripts (`lib/`) and source them in your main scripts using `source lib/string_utils.sh` or `. lib/string_utils.sh`.
|
||||
* **Modular Design:** Aim for a modular design where each module can be easily tested and reused in other projects.
|
||||
# ... rest of the script
|
||||
```
|
||||
|
||||
### 1.4. Component Architecture
|
||||
### 1.3 Functions and `main` Entry Point
|
||||
Encapsulate all script logic within functions. Use a `main` function as the primary entry point. This improves readability, reusability, and variable scoping.
|
||||
|
||||
* **Functions as Components:** Treat functions as components with well-defined inputs (parameters) and outputs (return values or side effects).
|
||||
* **Configuration Management:** Use configuration files to store settings that can be easily modified without changing the script's code.
|
||||
* **Logging:** Implement a consistent logging mechanism to track script execution and errors.
|
||||
❌ BAD:
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
# Script logic directly in the global scope
|
||||
echo "Starting operation..."
|
||||
ls -l /tmp
|
||||
# ...
|
||||
```
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
✅ GOOD:
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
* **Function Decomposition:** Break down complex tasks into smaller, more manageable functions.
|
||||
* **File Inclusion:** Use `source` or `.` to include reusable code from other files.
|
||||
* **External Commands:** Delegate tasks to external commands when appropriate (e.g., `grep`, `sed`, `awk`).
|
||||
* **Consider a 'main' function:** Wrap the primary logic of the script into a `main` function to improve readability and maintainability. All scripts that are long enough to contain at least one other function should have a `main` function.
|
||||
# ... file header ...
|
||||
|
||||
# Performs a specific sub-task.
|
||||
# Arguments:
|
||||
# $1 - The item to process.
|
||||
process_item() {
|
||||
local item="${1}"
|
||||
echo "Processing: ${item}"
|
||||
# ...
|
||||
}
|
||||
|
||||
# Main entry point for the script.
|
||||
# Arguments:
|
||||
# $@ - All command-line arguments.
|
||||
main() {
|
||||
echo "Script started."
|
||||
for arg in "$@"; do
|
||||
process_item "${arg}"
|
||||
done
|
||||
echo "Script finished."
|
||||
}
|
||||
|
||||
# Call the main function with all script arguments.
|
||||
main "$@"
|
||||
```
|
||||
|
||||
### 1.4 Variable Scoping and Naming
|
||||
Declare variables with `local` inside functions. Use `UPPER_SNAKE_CASE` for global `readonly` constants and `lower_snake_case` for local variables and function names.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
GLOBAL_VAR="value" # Not readonly, could be modified
|
||||
my_func() {
|
||||
temp_var="another_value" # Not local, pollutes global scope
|
||||
}
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
readonly CONFIG_FILE="/etc/my_app/config.conf" # Global constant
|
||||
readonly LOG_LEVEL="INFO"
|
||||
|
||||
my_function() {
|
||||
local temp_message="This is a local message."
|
||||
echo "${LOG_LEVEL}: ${temp_message}"
|
||||
# ...
|
||||
}
|
||||
|
||||
main() {
|
||||
my_function
|
||||
}
|
||||
|
||||
main "$@"
|
||||
```
|
||||
|
||||
### 1.5 Indentation and Line Length
|
||||
Use 2 spaces for indentation. Limit lines to approximately 80 characters. Break long lines with backslashes `\` for readability.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
if [[ "${long_variable_name_one}" == "${long_variable_name_two}" && "${another_long_variable}" -gt 100 ]]; then echo "This line is way too long and hard to read."; fi
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
if [[ "${long_variable_name_one}" == "${long_variable_name_two}" && \
|
||||
"${another_long_variable}" -gt 100 ]]; then
|
||||
echo "This line is readable."
|
||||
fi
|
||||
```
|
||||
|
||||
### 1.6 Cleanup with `trap`
|
||||
Use `trap` to ensure resources (e.g., temporary files) are cleaned up even if the script exits unexpectedly.
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
readonly TMP_DIR="$(mktemp -d)"
|
||||
|
||||
cleanup() {
|
||||
echo "Cleaning up temporary directory: ${TMP_DIR}" >&2
|
||||
rm -rf "${TMP_DIR}"
|
||||
}
|
||||
|
||||
# Trap EXIT, INT (Ctrl+C), and TERM signals to run cleanup
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
main() {
|
||||
echo "Working in temporary directory: ${TMP_DIR}"
|
||||
touch "${TMP_DIR}/temp_file.txt"
|
||||
# ... script logic ...
|
||||
# No need to explicitly call cleanup, trap handles it.
|
||||
}
|
||||
|
||||
main "$@"
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns
|
||||
|
||||
* **Facade:** Create a simplified interface to a complex set of functions or modules.
|
||||
* **Strategy:** Define a family of algorithms and encapsulate each one in a separate function, making them interchangeable.
|
||||
* **Template Method:** Define the skeleton of an algorithm in a function, deferring some steps to subfunctions.
|
||||
* **Chain of Responsibility:** Pass a request along a chain of functions until one of them handles it.
|
||||
* **Singleton (Carefully):** Use sparingly for global configuration, initialize only once.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **String Manipulation:** Use Bash's built-in string manipulation features (e.g., parameter expansion, substring extraction) instead of external commands like `sed` or `awk` when possible.
|
||||
* **File Handling:** Use Bash's built-in file handling commands (e.g., `read`, `write`, `mkdir`, `rm`) for basic operations. For more complex operations, consider `find` with `-exec` or `xargs`.
|
||||
* **Looping:** Use `for` loops for iterating over lists of items and `while` loops for conditional execution.
|
||||
* **Conditional Statements:** Use `if`, `elif`, and `else` statements for branching logic. Prefer `[[ ]]` over `[ ]` for string comparisons.
|
||||
* **Exit Early:** Use `return` or `exit` to exit the script as soon as an error is detected.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells
|
||||
|
||||
* **Hardcoded Values:** Avoid hardcoding values directly in the script. Use constants or configuration files instead.
|
||||
* **Unquoted Variables:** Always quote variables to prevent word splitting and globbing issues.
|
||||
* **Eval:** Avoid using `eval` as it can introduce security vulnerabilities and make the code difficult to understand.
|
||||
* **Backticks:** Use `$(command)` instead of backticks for command substitution.
|
||||
* **Relying on Globals:** Minimize the use of global variables to avoid naming conflicts and unexpected side effects. Use `local` within functions.
|
||||
* **Ignoring Errors:** Always check the return values of commands to handle errors gracefully. Use `set -e` to exit on errors automatically.
|
||||
* **Over-commenting Obvious Code:** Comments should explain *why* the code is doing something, not *what* the code is doing.
|
||||
* **Excessive Piping:** While powerful, long pipelines can become unreadable. Consider breaking down complex operations into smaller, more manageable steps with intermediate variables.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Environment Variables:** Use environment variables to store global configuration settings that can be accessed by all scripts and functions.
|
||||
* **Temporary Files:** Use temporary files to store intermediate data during script execution. Use `mktemp` to create unique temporary file names and remove them when finished. They should be created under `/tmp` or another location if needed.
|
||||
* **Persistent Storage:** For persistent state, consider using a simple database (e.g., SQLite) or a key-value store (e.g., Redis).
|
||||
* **Configuration Files:** Store persistent configuration options in configuration files.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **`set -e`:** Exit immediately if a command exits with a non-zero status.
|
||||
* **Check Return Values:** Use `$?` to check the return value of a command and handle errors accordingly.
|
||||
* **Error Functions:** Create functions to handle common error scenarios (e.g., logging errors, displaying error messages, exiting the script).
|
||||
* **Signal Handling:** Use `trap` to handle signals (e.g., `SIGINT`, `SIGTERM`) and perform cleanup actions.
|
||||
* **Informative Error Messages:** Provide clear and informative error messages to help users diagnose problems. The error messages should explain the cause and possibly the recommended solution.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Built-in Commands:** Prefer built-in commands over external commands whenever possible, as they are generally faster.
|
||||
* **String Operations:** Use Bash's built-in string manipulation features instead of external commands like `sed` or `awk` for simple operations.
|
||||
* **Avoid Loops:** Minimize the use of loops, as they can be slow in Bash. Consider using `find` with `-exec` or `xargs` for file processing instead.
|
||||
* **Command Substitution:** Avoid unnecessary command substitution, as it can be expensive.
|
||||
* **Arrays:** Use arrays to store lists of items instead of strings, as they are more efficient for iteration and manipulation.
|
||||
* **Parameter Expansion:** Use parameter expansion features like `${var:-default}` to provide default values for variables without using conditional statements.
|
||||
* **`set -f`:** Disable globbing when not needed to prevent unintended file expansion.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Limit Data Size:** Avoid loading large files or data structures into memory.
|
||||
* **Stream Processing:** Use stream processing techniques to process data incrementally instead of loading it all into memory at once.
|
||||
* **Remove Variables:** Unset or reassign variables to release memory when they are no longer needed.
|
||||
|
||||
### 3.3. Rendering Optimization (If Applicable)
|
||||
|
||||
* **Minimize Output:** Reduce the amount of output generated by the script, as it can slow down execution.
|
||||
* **Use `printf`:** Use `printf` for formatted output instead of `echo`, as it is generally faster and more portable.
|
||||
|
||||
### 3.4. Bundle Size Optimization (If Applicable)
|
||||
|
||||
* **N/A:** Bash scripts do not typically have bundle sizes in the same way that web applications do.
|
||||
|
||||
### 3.5. Lazy Loading
|
||||
|
||||
* **Source on Demand:** Only source library scripts when they are needed.
|
||||
* **Conditional Execution:** Use conditional statements to execute code blocks only when certain conditions are met.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and Prevention
|
||||
|
||||
* **Command Injection:** Avoid using `eval` and carefully sanitize any user input used in commands.
|
||||
* **Path Injection:** Sanitize path names to prevent malicious users from manipulating file operations.
|
||||
* **Denial of Service (DoS):** Implement resource limits to prevent scripts from consuming excessive CPU, memory, or disk space.
|
||||
* **Information Disclosure:** Protect sensitive information (e.g., passwords, API keys) by storing them in environment variables or configuration files with appropriate permissions.
|
||||
* **Shellshock:** Ensure your Bash version is patched against the Shellshock vulnerability.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Sanitize User Input:** Carefully sanitize any user input to prevent command injection and other vulnerabilities.
|
||||
* **Regular Expressions:** Use regular expressions to validate input formats (e.g., email addresses, phone numbers).
|
||||
* **Whitelist Validation:** Validate input against a whitelist of allowed values.
|
||||
* **Length Limits:** Enforce length limits on input fields to prevent buffer overflows.
|
||||
|
||||
### 4.3. Authentication and Authorization
|
||||
|
||||
* **Avoid Storing Credentials:** Avoid storing credentials directly in scripts or configuration files. Use environment variables or a secure credential store instead.
|
||||
* **Principle of Least Privilege:** Run scripts with the minimum necessary privileges.
|
||||
* **User Authentication:** Implement user authentication using `sudo` or other authentication mechanisms.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to restrict access to sensitive resources based on user roles.
|
||||
|
||||
### 4.4. Data Protection
|
||||
|
||||
* **Encryption:** Use encryption to protect sensitive data at rest and in transit.
|
||||
* **Data Masking:** Mask sensitive data in log files and other output.
|
||||
* **Access Control:** Restrict access to sensitive data to authorized users only.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
|
||||
* **API Keys:** Use API keys to authenticate requests to external APIs.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
|
||||
* **Input Validation:** Validate all input from external APIs to prevent injection attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing
|
||||
|
||||
* **Test Individual Functions:** Write unit tests to verify the behavior of individual functions.
|
||||
* **Mock Dependencies:** Use mocking techniques to isolate functions from their dependencies.
|
||||
* **Assert Statements:** Use assert statements to verify that the functions return the expected values.
|
||||
* **Testing Frameworks:** Consider using a bash testing framework like Bats (Bash Automated Testing System).
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test Interactions:** Write integration tests to verify the interactions between different modules or components.
|
||||
* **Real Environments:** Run integration tests in a real or simulated environment.
|
||||
* **End-to-End Testing:** Write end-to-end tests to verify the entire script from start to finish.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Real Use Cases:** Emulate real-world use cases to test the script's overall functionality.
|
||||
* **System-Level Testing:** Verify that the script interacts correctly with the underlying system.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Separate Test Directory:** Create a separate `tests/` directory to store test files.
|
||||
* **Naming Convention:** Use a consistent naming convention for test files (e.g., `module_name_test.sh`).
|
||||
* **Test Suites:** Organize tests into suites based on functionality or module.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock External Commands:** Create mock versions of external commands to isolate functions from their dependencies.
|
||||
* **Stub Functions:** Create stub versions of functions to control their behavior during testing.
|
||||
* **Environment Variable Mocking:** Mock environment variables to test different configurations.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes
|
||||
|
||||
* **Forgetting `set -e`:** Not exiting on errors can lead to unexpected behavior.
|
||||
* **Unquoted Variables:** Forgetting to quote variables can lead to word splitting and globbing issues.
|
||||
* **Incorrect Variable Scope:** Using global variables when local variables are needed can lead to naming conflicts.
|
||||
* **Not Checking Return Values:** Not checking return values can lead to errors being ignored.
|
||||
* **Over-reliance on Globals** Using global variables when local variables are preferable can lead to unintended side effects.
|
||||
* **Not using Functions** Code becomes difficult to maintain if its not broken into manageable functions.
|
||||
|
||||
### 6.2. Edge Cases
|
||||
|
||||
* **Empty Variables:** Handle empty variables gracefully.
|
||||
* **Special Characters:** Handle special characters in file names and other input.
|
||||
* **Large Files:** Handle large files efficiently to prevent memory issues.
|
||||
* **Race Conditions:** Avoid race conditions when multiple scripts are running concurrently.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Bash 3 vs. Bash 4:** Be aware of compatibility issues between different versions of Bash.
|
||||
* **POSIX Compliance:** If portability is a concern, stick to POSIX-compliant syntax.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Operating Systems:** Ensure your scripts are compatible with the target operating systems.
|
||||
* **External Tools:** Be aware of the dependencies on external tools and ensure they are available on the target systems.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **`set -x`:** Enable tracing to see the commands being executed.
|
||||
* **`echo` Statements:** Use `echo` statements to print variable values and debug messages.
|
||||
* **Shellcheck:** Use Shellcheck to identify common errors and warnings.
|
||||
* **Interactive Debugging:** Use an interactive debugger like `bashdb` to step through the code.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **Text Editor:** Use a text editor with syntax highlighting and code completion for Bash (e.g., VS Code, Sublime Text, Vim).
|
||||
* **Shellcheck:** Use Shellcheck to lint your Bash code.
|
||||
* **Bats:** Use Bats for unit testing.
|
||||
* **Bashdb:** Use Bashdb for interactive debugging.
|
||||
* **Git:** Use Git for version control.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **Makefile:** Use a Makefile to automate build and test processes.
|
||||
* **Dependency Management:** Use a dependency management tool like `dep` to manage external dependencies.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **Shellcheck:** Use Shellcheck to lint your Bash code and enforce coding standards.
|
||||
* **shfmt:** Use shfmt for automatic code formatting.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Package Scripts:** Package your scripts and dependencies into a deployable package (e.g., Debian package, RPM package).
|
||||
* **Configuration Management:** Use configuration management tools (e.g., Ansible, Puppet, Chef) to deploy and configure your scripts on target systems.
|
||||
* **Automated Deployment:** Use automated deployment pipelines to deploy your scripts quickly and reliably.
|
||||
* **Idempotent Scripts:** Ensure your deployment scripts are idempotent, meaning they can be run multiple times without causing unintended side effects.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **Continuous Integration (CI):** Integrate your Bash scripts into a CI pipeline to automatically run tests and linting on every commit.
|
||||
* **Continuous Deployment (CD):** Integrate your Bash scripts into a CD pipeline to automatically deploy your scripts to production.
|
||||
|
||||
## 8. Naming Conventions
|
||||
|
||||
Follow these naming conventions:
|
||||
|
||||
* **Function Names:** Lowercase, with underscores to separate words (e.g., `process_data`, `calculate_total`).
|
||||
* **Variable Names:** Lowercase, with underscores to separate words (e.g., `input_file`, `output_directory`). Loop variables should be similarly named for the variable you're looping through.
|
||||
* **Constant Names:** All caps, separated with underscores (e.g., `MAX_RETRIES`, `DEFAULT_TIMEOUT`). Declared at the top of the file.
|
||||
* **File Names:** Lowercase, with underscores to separate words (e.g., `data_processing.sh`, `configuration_settings.conf`).
|
||||
|
||||
## 9. Style and Formatting
|
||||
|
||||
* **Indentation:** Use 2 spaces for indentation. No tabs.
|
||||
* **Line Length:** Limit lines to 80 characters. Use line continuation characters (`\`) to break long lines.
|
||||
* **Spacing:** Use spaces around operators and after commas.
|
||||
* **Comments:** Write clear and concise comments to explain the purpose and logic of your code. Any function that is not both obvious and short must be commented. Any function in a library must be commented regardless of length or complexity. Use `TODO` comments to mark code that needs to be improved or completed.
|
||||
* **Quoting:** Always quote variables unless careful unquoted expansion is required.
|
||||
* **Braces:** Use `${variable}` instead of `$variable` for clarity.
|
||||
* **Pipelines:** Format pipelines for maximum clarity. Break long pipelines into multiple lines with one pipeline element per line.
|
||||
|
||||
## 10. Exit Codes
|
||||
* Ensure exit codes are consistent throughout the scripts.
|
||||
* Use `exit 0` for successful completion.
|
||||
* Use non-zero exit codes (e.g., 1, 2, 127, etc.) to indicate failure.
|
||||
* Standardize exit codes for specific error conditions across your project.
|
||||
* Include custom error messages with meaningful context.
|
||||
|
||||
Following these best practices and coding standards will help you write more maintainable, readable, secure, and efficient Bash scripts.
|
||||
### 2.1 Always Quote Variables and Command Substitutions
|
||||
This is the single most important rule. Always double-quote variable expansions (`"${var}"`) and use `$(command)` for command substitution to prevent word splitting and globbing.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
files="file1.txt file with spaces.txt"
|
||||
for f in $files; do # Word splitting occurs
|
||||
echo "Processing: $f" # Unquoted, will cause issues with spaces/globs
|
||||
done
|
||||
|
||||
output=`ls -l` # Deprecated backticks
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
files=("file1.txt" "file with spaces.txt") # Use arrays for lists
|
||||
for f in "${files[@]}"; do # Correctly iterates over array elements
|
||||
echo "Processing: \"${f}\"" # Quoted, handles spaces correctly
|
||||
done
|
||||
|
||||
output=$(ls -l) # Modern command substitution
|
||||
```
|
||||
|
||||
### 2.2 Prefer `[[ ... ]]` for Conditionals
|
||||
Use the bash-specific `[[ ... ]]` construct over `[ ... ]` (test). `[[ ... ]]` is safer, handles quoting internally, and supports advanced features like regex matching (`=~`).
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
if [ "$my_var" = "value" ]; then # Prone to issues if my_var is empty or contains spaces
|
||||
echo "Legacy test"
|
||||
fi
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
if [[ "${my_var}" == "value" ]]; then # Safer, quoting generally recommended for clarity
|
||||
echo "Modern test"
|
||||
fi
|
||||
|
||||
# Regex matching
|
||||
if [[ "${filename}" =~ \.log$ ]]; then
|
||||
echo "It's a log file."
|
||||
fi
|
||||
```
|
||||
|
||||
### 2.3 Use Long Options for Readability
|
||||
Prefer long-form command options (`--recursive`) over short-form (`-r`) in scripts for improved readability.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
rm -rf "${dir}"
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
rm --recursive --force -- "${dir}" # -- to separate options from arguments
|
||||
```
|
||||
|
||||
### 2.4 Redirect Errors to `STDERR`
|
||||
Ensure all error messages and diagnostic output go to `STDERR` (`>&2`), reserving `STDOUT` for the intended program output.
|
||||
|
||||
```bash
|
||||
log_error() {
|
||||
printf "[ERROR] %s: %s\n" "$(date '+%Y-%m-%dT%H:%M:%S%z')" "${*}" >&2
|
||||
}
|
||||
|
||||
if ! some_command; then
|
||||
log_error "Failed to execute some_command."
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
### 2.5 Heredocs for Multi-line Strings
|
||||
Use heredocs for multi-line strings. Quote the tag (`<<'EOF'`) to prevent variable expansion and command substitution within the heredoc.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
echo "Hello ${USER},"
|
||||
echo "This is a multi-line message."
|
||||
echo "Current date: $(date)"
|
||||
```
|
||||
|
||||
✅ GOOD (Literal):
|
||||
```bash
|
||||
cat <<'EOF'
|
||||
Hello ${USER},
|
||||
This is a literal multi-line message.
|
||||
Current date: $(date)
|
||||
EOF
|
||||
```
|
||||
|
||||
✅ GOOD (Interpolated):
|
||||
```bash
|
||||
cat <<EOF
|
||||
Hello ${USER},
|
||||
This is an interpolated multi-line message.
|
||||
Current date: $(date)
|
||||
EOF
|
||||
```
|
||||
|
||||
### 2.6 Arithmetic with `(( ... ))`
|
||||
Use `(( ... ))` for arithmetic operations. It's cleaner and safer than `expr` or `let`.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
COUNT=`expr $COUNT + 1`
|
||||
let COUNT=COUNT+1
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
count=0
|
||||
((count++))
|
||||
echo "${count}" # Output: 1
|
||||
|
||||
num_a=10
|
||||
num_b=5
|
||||
result=$((num_a * num_b))
|
||||
echo "${result}" # Output: 50
|
||||
```
|
||||
|
||||
### 2.7 Scoped Directory Changes
|
||||
When changing directories, use a subshell `(cd ...)` or `pushd`/`popd` to ensure the change is temporary and doesn't affect the rest of the script.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
cd /tmp/my_app
|
||||
# ... operations ...
|
||||
cd - # Easy to forget, or fail if previous dir is gone
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
(
|
||||
cd /tmp/my_app || exit 1 # Subshell, changes only apply here
|
||||
echo "Current directory in subshell: $(pwd)"
|
||||
# ... operations ...
|
||||
)
|
||||
echo "Current directory outside subshell: $(pwd)" # Original directory
|
||||
```
|
||||
|
||||
## 3. Common Pitfalls and Gotchas
|
||||
|
||||
### 3.1 `while read` in a Pipe
|
||||
Variables set inside a `while read` loop that is part of a pipeline will not persist outside the loop, as the loop runs in a subshell.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
count=0
|
||||
ls | while read -r file; do
|
||||
((count++)) # count is modified in a subshell
|
||||
done
|
||||
echo "Total files: ${count}" # Will likely be 0
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
count=0
|
||||
# Use process substitution or redirect file directly
|
||||
while read -r file; do
|
||||
((count++))
|
||||
done < <(ls) # Process substitution
|
||||
echo "Total files: ${count}" # Correct count
|
||||
|
||||
# Alternative: mapfile (Bash 4+)
|
||||
mapfile -t files_array < <(ls)
|
||||
count="${#files_array[@]}"
|
||||
echo "Total files: ${count}"
|
||||
```
|
||||
|
||||
### 3.2 `sudo` with Redirection
|
||||
Redirection (`>`) happens *before* `sudo` executes the command. To write to a root-owned file, run the entire command under `sudo`.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
echo "Sensitive data" > /root/protected_file # Redirection by current user
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
echo "Sensitive data" | sudo tee /root/protected_file > /dev/null
|
||||
# OR
|
||||
sudo bash -c 'echo "Sensitive data" > /root/protected_file'
|
||||
```
|
||||
|
||||
### 3.3 Avoid `eval`
|
||||
`eval` is a security risk and makes scripts hard to debug. Avoid it unless absolutely necessary and you fully control the input.
|
||||
|
||||
❌ BAD:
|
||||
```bash
|
||||
user_input="rm -rf /"
|
||||
eval "${user_input}" # Dangerous!
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```bash
|
||||
# Refactor to avoid eval. Use case statements, arrays, or functions instead.
|
||||
# If dynamic command execution is truly needed, validate and sanitize input rigorously.
|
||||
```
|
||||
|
||||
## 4. Testing Approaches
|
||||
|
||||
### 4.1 `shellcheck`
|
||||
Integrate `shellcheck` into your workflow. It's an invaluable static analysis tool that catches common pitfalls and warns about bad practices.
|
||||
|
||||
```bash
|
||||
# Run shellcheck on your script
|
||||
shellcheck myscript.sh
|
||||
```
|
||||
|
||||
### 4.2 Debugging with `set -x`
|
||||
Use `set -x` (xtrace) for debugging. It prints each command and its arguments after expansion. Localize its use to specific sections.
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
my_debug_function() {
|
||||
set -x # Start tracing
|
||||
local debug_var="hello"
|
||||
echo "Debug var: ${debug_var}"
|
||||
set +x # Stop tracing
|
||||
}
|
||||
|
||||
main() {
|
||||
echo "Before debug function."
|
||||
my_debug_function
|
||||
echo "After debug function."
|
||||
}
|
||||
|
||||
main "$@"
|
||||
```
|
||||
|
||||
### 4.3 Syntax Check with `bash -n`
|
||||
Before running, perform a dry run to check for syntax errors.
|
||||
|
||||
```bash
|
||||
bash -n myscript.sh
|
||||
```
|
||||
Reference in New Issue
Block a user