Problem Statement
Explain the basic structure of a well-written shell script including shebang, comments, error handling, and style conventions.
Explanation
Start with proper shebang: #!/bin/bash or #!/bin/sh depending on required features. Add script description comments at top explaining purpose, usage, author, and date. Example:
```bash
#!/bin/bash
# Script: backup.sh
# Purpose: Backup specified directory
# Usage: ./backup.sh <source_dir> <dest_dir>
# Author: John Doe
# Date: 2024-01-15
```
Enable strict mode for safer scripts: set -e (exit on error), set -u (exit on undefined variable), set -o pipefail (pipeline returns failure if any command fails). Together: set -euo pipefail catches more errors. Add IFS=$'\n\t' to prevent word splitting issues. Use 'set -x' for debugging (prints each command before execution).
Structure script logically: parse arguments and validate input first, define functions for reusable code, main script logic, cleanup on exit using trap. Example:
```bash
trap cleanup EXIT
function cleanup() { rm -f "$TEMP_FILE"; }
function usage() { echo "Usage: $0 <arg>"; exit 1; }
[ $# -eq 0 ] && usage
main_logic_here
```
Style conventions: use meaningful variable names in UPPER_CASE for constants, lower_case for local variables, use functions for repeated code, comment complex logic, validate inputs before use, check exit status of important commands, provide helpful error messages with context, and use constants for file paths and configuration. Indent consistently (2 or 4 spaces), use snake_case for function names, and quote variables consistently.
Error handling: check critical command results: if ! command; then echo "Error: command failed"; exit 1; fi. Validate file existence: [ -f "$FILE" ] || { echo "File not found"; exit 1; }. Provide usage help: if [ $# -ne 2 ]; then echo "Usage: $0 arg1 arg2"; exit 1; fi. Log errors to stderr: echo "Error" >&2. Understanding these practices creates maintainable, reliable scripts.