Code_style
Chapter 35: Code Style and Organization
Section titled “Chapter 35: Code Style and Organization”Overview
Section titled “Overview”This chapter covers how to organize and style bash scripts for better maintainability, readability, and collaboration.
Code Organization
Section titled “Code Organization”Directory Structure
Section titled “Directory Structure”project/├── bin/│ ├── main.sh│ └── functions.sh├── lib/│ ├── config.sh│ └── utils.sh├── conf/│ └── app.conf├── logs/└── README.mdScript Types
Section titled “Script Types”/usr/local/bin/ # User scripts/etc/scripts/ # System scripts/opt/app/bin/ # Application scripts~/scripts/ # Personal scriptsNaming Conventions
Section titled “Naming Conventions”Files and Scripts
Section titled “Files and Scripts”# Use descriptive namesdeploy.shbackup_database.shmonitor_services.sh
# Avoid abbreviations (except well-known)nginx_conf.sh # OKng_c.sh # Not good
# Use kebab-case or snake_casedeploy.sh # kebab-casedeploy_script.sh # snake_caseVariables
Section titled “Variables”# Constants - UPPERCASEreadonly MAX_RETRIES=3readonly DEFAULT_PORT=8080
# Variables - lowercaselocal count=0local input_file=""
# Arrays - plural or suffixlocal files=()local file_list=()
# Associative arrays - descriptivedeclare -A user_configdeclare -A server_portsFunctions
Section titled “Functions”# Use descriptive namescheck_service_health()deploy_application()backup_database()
# Use verb-noun patterndeploy()install()update()Code Layout
Section titled “Code Layout”Indentation
Section titled “Indentation”# Use 4 spaces (not tabs)function example() { if [[ condition ]]; then echo "Hello" fi}Line Length
Section titled “Line Length”# Keep lines under 80 characters# Break long commandscurl -X POST \ -H "Content-Type: application/json" \ -d '{"key": "value"}' \ http://api.example.com/endpoint
# Use variables for long valuesreadonly API_ENDPOINT="http://api.example.com/v1"curl -X POST "$API_ENDPOINT/endpoint"Spacing
Section titled “Spacing”# Spaces around operatorslocal sum=$((a + b))local result="${var//old/new}"
# No spaces in testsif [[ $a -eq $b ]]; then echo "Equal"fi
# Spaces after commasarray=(one two three)local item="${array[0]}"Comments
Section titled “Comments”Comment Style
Section titled “Comment Style”#!/bin/bash## Script description## Author: Your Name# Version: 1.0.0#
# Section comments# ==================# Configuration# ==================
# Function comments# process_file - Processes input file# Arguments:# $1 - input file path# Returns:# 0 on success, 1 on failureprocess_file() { # Inline comments local file="$1" # Input file}
# TODO comments# TODO: Add error handling# FIXME: Fix this bugFunctions
Section titled “Functions”Function Organization
Section titled “Function Organization”# Put main function at the bottom# Put helper functions first
# Order:# 1. Imports/source files# 2. Global variables# 3. Helper functions# 4. Main functions# 5. Entry point
# Example order:# source lib/utils.sh# readonly CONFIG_FILE="..."
# log()# error()# cleanup()
# deploy()# backup()# restore()
# main()main "$@"Function Structure
Section titled “Function Structure”# Standard function templatefunction_name() { # Description comment
# Arguments local arg1="$1" local arg2="${2:-default}"
# Local variables local result=""
# Function body if condition; then result="value" fi
# Return value or status echo "$result" return 0}Testing Functions
Section titled “Testing Functions”Simple Test Framework
Section titled “Simple Test Framework”#!/bin/bash
# Test runnerrun_test() { local test_name="$1" local test_func="$2"
echo -n "Testing: $test_name... " if $test_func; then echo "PASS" ((PASSED++)) else echo "FAIL" ((FAILED++)) fi}
# Test functionstest_example() { [[ $(echo "hello" | tr 'a-z' 'A-Z') == "HELLO" ]]}
# Run testsrun_test "Example test" test_exampleVersion Control
Section titled “Version Control”Gitignore
Section titled “Gitignore”# .gitignore for bash projects
# Logs*.loglogs/
# Temporary files*.tmp*.swp*~
# Backups*.bak*.backup
# Secrets.env*.pem*.key
# Build outputbuild/dist/Commit Messages
Section titled “Commit Messages”feat: Add deployment scriptfix: Fix backup rotationdocs: Update READMErefactor: Simplify config loadingtest: Add unit testsDocumentation
Section titled “Documentation”README Structure
Section titled “README Structure”# README.md
# Project NameShort description
## Installation\`\`\`bash./install.sh\`\`\`
## Usage\`\`\`bash./script.sh -f input.txt\`\`\`
## ConfigurationSet these environment variables:- VAR_NAME: Description
## LicenseMITshellcheck
Section titled “shellcheck”# Installsudo pacman -S shellcheck
# Runshellcheck script.sh
# With optionsshellcheck -x script.sh # Allow sourceshellcheck -e SC1090 script.sh# Installgo install mvdan.cc/sh/v3/cmd/shfmt@latest
# Formatshfmt -w script.sh
# With optionsshfmt -l -w -i 4 script.shBest Practices Summary
Section titled “Best Practices Summary”- Use descriptive names
- Comment complex code
- Keep functions small and focused
- Use strict mode
- Test your scripts
- Use version control
Don’ts
Section titled “Don’ts”- Don’t use one-letter variables
- Don’t hardcode secrets
- Don’t use deprecated syntax
- Don’t ignore shellcheck warnings
- Don’t write spaghetti code
Summary
Section titled “Summary”In this chapter, you learned:
- ✅ Code organization (directories, scripts)
- ✅ Naming conventions (files, variables, functions)
- ✅ Code layout (indentation, line length, spacing)
- ✅ Commenting best practices
- ✅ Function organization
- ✅ Testing framework
- ✅ Version control and .gitignore
- ✅ README documentation
- ✅ Tools (shellcheck, shfmt)
Next Steps
Section titled “Next Steps”Continue to the next chapter to learn about System Administration Scripts.
Previous Chapter: Common One-liners Next Chapter: System Administration Scripts