Skip to content

Instantly share code, notes, and snippets.

@aaronpeters
Last active February 21, 2025 11:20
Show Gist options
  • Save aaronpeters/2b67820e903e63814d2b5d42fbc854c5 to your computer and use it in GitHub Desktop.
Save aaronpeters/2b67820e903e63814d2b5d42fbc854c5 to your computer and use it in GitHub Desktop.
Bash script to check presence of specific response header
#!/bin/bash
# Use case: measure CDN change propagation time (CPT)
# Change the CDN config in CDN control panel or API,
# so CDN servers a new response header.
# Next, run this script to check after how many seconds
# the CDN serves a response with that header
# For example, change CDN config to start serving the x-cdn header
# Run this script then with command
# ./check_header.sh HEADER=x-cdn DEBUG=1
# Default values for the variables
DEFAULT_URL='https://cdnpnodes.mncdn.com/static/15kb.png'
DEFAULT_HEADER='date'
DEFAULT_DEBUG=1
DEFAULT_MAX_TIME=90
# Assign command-line arguments or use defaults
for arg in "$@"; do
case $arg in
URL=*) URL="${arg#*=}" ;;
HEADER=*) HEADER="${arg#*=}" ;;
DEBUG=*) DEBUG="${arg#*=}" ;;
MAX_TIME=*) MAX_TIME="${arg#*=}" ;;
*) echo "Invalid argument: $arg" ;;
esac
done
# Set defaults if not provided
URL=${URL:-$DEFAULT_URL}
HEADER=${HEADER:-$DEFAULT_HEADER}
DEBUG=${DEBUG:-$DEFAULT_DEBUG}
MAX_TIME=${MAX_TIME:-$DEFAULT_MAX_TIME}
COUNT=0 # Initialize request counter
START_TIME=$(date +%s) # Record the start time
# Echo the test settings
echo -e "Test settings:\nURL: $URL\nHEADER: $HEADER\nDEBUG: $DEBUG\nMAX_TIME: $MAX_TIME seconds\n"
while true; do
CURRENT_TIME=$(date +%s)
ELAPSED_TIME=$((CURRENT_TIME - START_TIME))
# Check if the elapsed time has exceeded the max time
if [ "$ELAPSED_TIME" -ge "$MAX_TIME" ]; then
echo -e "\nHeader $HEADER not found within $MAX_TIME seconds."
break
fi
COUNT=$((COUNT + 1))
# Send the HTTP request and capture the headers separately
response_headers=$(mktemp)
curl -s -D "$response_headers" -o /dev/null "$URL"
# Extract the status code for both HTTP/1.1 and HTTP/2
status_code=$(awk '/HTTP\// {print $2}' "$response_headers" | head -n1)
# Check if the specific header is present with exact matching (case-insensitive)
if grep -iq "^$HEADER: " "$response_headers"; then
echo -e "$status_code, Header $HEADER found!\n"
# Print all response headers
cat "$response_headers"
echo -e "\nNumber of requests made: $COUNT"
echo -e "Script run time (seconds): $ELAPSED_TIME\n"
rm "$response_headers" # Clean up temporary file
break
else
echo -e "$status_code, Header $HEADER not found\n"
# Print all response headers if DEBUG is enabled
if [ "$DEBUG" -eq 1 ]; then
cat "$response_headers"
fi
rm "$response_headers" # Clean up temporary file
fi
# Wait for 5 seconds before the next request
sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment