Bash Script to Check Website Status Quickly
curl -Is https://example.com | head -n 1 in a Bash script to check the website status line, or use curl -o /dev/null -s -w "%{http_code}" https://example.com to get just the HTTP status code.Examples
How to Think About It
curl to fetch headers silently and extracts the first line or the HTTP status code to know if the site is reachable and what status it returns.Algorithm
Code
#!/bin/bash url="$1" if [ -z "$url" ]; then echo "Usage: $0 <website_url>" exit 1 fi status_code=$(curl -o /dev/null -s -w "%{http_code}" "$url") echo "Status code for $url is: $status_code"
Dry Run
Let's trace checking https://www.google.com through the code
Get input URL
url="https://www.google.com"
Run curl to get status code
status_code=$(curl -o /dev/null -s -w "%{http_code}" "https://www.google.com") status_code="200"
Print the status code
echo "Status code for https://www.google.com is: 200"
| Step | Action | Value |
|---|---|---|
| 1 | Input URL | https://www.google.com |
| 2 | curl status code | 200 |
| 3 | Output message | Status code for https://www.google.com is: 200 |
Why This Works
Step 1: Input URL
The script takes the website URL as input using $1, which is the first argument passed to the script.
Step 2: Fetch status code
It uses curl with options -o /dev/null to discard body, -s for silent mode, and -w "%{http_code}" to output only the HTTP status code.
Step 3: Display result
The script prints the status code with a message so you know if the website is reachable and what response it gave.
Alternative Approaches
#!/bin/bash url="$1" if [ -z "$url" ]; then echo "Usage: $0 <website_url>" exit 1 fi status_line=$(curl -Is "$url" | head -n 1) echo "Status line for $url is: $status_line"
#!/bin/bash url="$1" wget --spider -S "$url" 2>&1 | grep 'HTTP/' | head -n 1
Complexity: O(1) time, O(1) space
Time Complexity
The script runs a single network request which takes constant time relative to input size, so O(1).
Space Complexity
Uses only a few variables to store input and output, so O(1) space.
Which Approach is Fastest?
Using curl with -o /dev/null -s -w is fastest and cleanest; alternatives like wget add overhead and more output parsing.
| Approach | Time | Space | Best For |
|---|---|---|---|
| curl with -w | O(1) | O(1) | Quick status code check |
| curl with -I and head | O(1) | O(1) | Full status line info |
| wget --spider | O(1) | O(1) | When curl is unavailable |