Skip to content

Instantly share code, notes, and snippets.

@TomCan
Created March 14, 2025 15:55
Show Gist options
  • Save TomCan/7667ca1f3ad13848e563b41ad6a8da11 to your computer and use it in GitHub Desktop.
Save TomCan/7667ca1f3ad13848e563b41ad6a8da11 to your computer and use it in GitHub Desktop.
Script to resolve/dump the apache2 config into a single file
#!/bin/bash
# Function to recursively process Apache config files
process_config_file() {
local file="$1"
local server_root="$2"
local indent="${3:-}"
# Check if file exists
if [[ ! -f "$file" ]]; then
echo "# Warning: File not found: $file" >&2
return
fi
if [[ "$file" =~ /sites-enabled/ ]]; then
echo "# Skipping sites-enabled file $file"
return
fi
echo ""
echo "### $file"
# Process the file line by line
while IFS= read -r line || [[ -n "$line" ]]; do
# Check if line is comment
if [[ "$line" =~ ^[[:space:]]*# ]]; then
# Ignore comment line. Don't output either.
continue
# Check if line is empty
elif [[ "$line" =~ ^$ ]]; then
# Ignore empty line. Don't output either.
continue
# Check if line updates ServerRoot
elif [[ "$line" =~ ^[[:space:]]*ServerRoot[[:space:]]+\"?\'?([^\"\']+)\"?\'? ]]; then
local new_server_root="${BASH_REMATCH[1]}"
echo "$line"
server_root="$new_server_root"
# Check if line contains Include or IncludeOptional
elif [[ "$line" =~ ^[[:space:]]*(Include|IncludeOptional)[[:space:]]+(.*) ]]; then
local directive="${BASH_REMATCH[1]}"
local pattern="${BASH_REMATCH[2]}"
# Remove quotes if present
pattern="${pattern//\"/}"
pattern="${pattern//\'/}"
# If pattern is relative (doesn't start with /), prepend ServerRoot
if [[ ! "$pattern" =~ ^/ ]]; then
pattern="$server_root/$pattern"
fi
# Expand the pattern and process each matching file
for included_file in $(ls -1 $pattern 2>/dev/null); do
process_config_file "$included_file" "$server_root" "${indent} "
done
# If Include and no files match, show warning
if [[ "$directive" == "Include" ]] && ! ls -1 $pattern &>/dev/null; then
echo "# ${indent}Warning: No files match pattern: $pattern" >&2
fi
else
# Output the line as is
echo "$line"
fi
done < "$file"
}
# Default ServerRoot
DEFAULT_SERVER_ROOT="/etc/apache2"
# Check if a file was provided as an argument
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <apache_config_file> [server_root]"
echo "Default server_root is $DEFAULT_SERVER_ROOT if not specified"
exit 1
fi
# Get the input file
CONFIG_FILE="$1"
# Get ServerRoot from arguments or use default
SERVER_ROOT="${2:-$DEFAULT_SERVER_ROOT}"
# Process the main config file
process_config_file "$CONFIG_FILE" "$SERVER_ROOT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment