Exit Codes and Script Status Reporting

Demonstrates proper exit code handling, error checking, set options for fail-safe behavior, and custom exit codes for script error reporting.

BashResilience

Code

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

# Custom exit codes
E_SUCCESS=0
E_NO_ARGS=1
E_FILE_NOT_FOUND=2
E_PERMISSION=3
E_DEPENDENCY=4

# Check dependencies
check_dependency() {
    if ! command -v "$1" &>/dev/null; then
        echo "Error: $1 is required but not installed" >&2
        exit "$E_DEPENDENCY"
    fi
}

# Main function with error handling
main() {
    local input_file="${1:-}"

    if [[ -z "$input_file" ]]; then
        echo "Usage: $0 <input-file>" >&2
        exit "$E_NO_ARGS"
    fi

    if [[ ! -f "$input_file" ]]; then
        echo "Error: File not found: $input_file" >&2
        exit "$E_FILE_NOT_FOUND"
    fi

    if [[ ! -r "$input_file" ]]; then
        echo "Error: Cannot read file: $input_file" >&2
        exit "$E_PERMISSION"
    fi

    local output
    if ! output=$(wc -l "$input_file" 2>&1); then
        echo "Error processing file: $output" >&2
        exit 1
    fi

    echo "$output"
    exit "$E_SUCCESS"
}

# Check required tools
for tool in grep sort wc; do
    check_dependency "$tool"
done

main "$@"