Skip to content

Instantly share code, notes, and snippets.

@PttCodingMan
Created May 8, 2025 08:13
Show Gist options
  • Save PttCodingMan/1d70a0d44c00fe49a4c2f288132fa7d1 to your computer and use it in GitHub Desktop.
Save PttCodingMan/1d70a0d44c00fe49a4c2f288132fa7d1 to your computer and use it in GitHub Desktop.
#!/bin/bash
# --- 在這裡定義您想要測試的網址 ---
# 每個網址用引號括起來,並用空格分隔
URLS_TO_CHECK=(
"http://www.google.com"
"https://wiki.changingtec.com"
"https://gitlab-k8s.chg.com.tw"
"https://harbor-k8s.chg.com.tw"
)
# --- 網址定義結束 ---
# 檢查 curl 是否已安裝
if ! command -v curl &> /dev/null; then
echo "錯誤:需要 'curl' 指令,但系統未安裝。"
echo "請先安裝 curl 後再執行此腳本。"
echo "例如,在 Debian/Ubuntu 上:sudo apt update && sudo apt install curl"
echo "在 Fedora/CentOS 上:sudo yum install curl 或 sudo dnf install curl"
exit 1
fi
# 函數:檢查單一網址
check_url() {
local url="$1"
local http_code
local result
local curl_output # 用來捕捉 curl 的錯誤訊息 (如果有的話)
# 使用 curl 獲取 HTTP 狀態碼
# -L: follow redirects (跟隨重導向)
# -s: silent mode (靜默模式)
# -o /dev/null: discard output (丟棄下載的內容)
# --head: fetch headers only (僅獲取標頭,對於檢查連通性通常更快)
# 如果遇到問題,可以移除 --head,讓 curl 執行 GET 請求,但仍然丟棄內容。
# -w '%{http_code}': output only the HTTP status code (僅輸出 HTTP 狀態碼)
# --connect-timeout 5: timeout for connection in seconds (連線超時時間 5 秒)
# --max-time 10: max time for the whole operation in seconds (總操作超時時間 10 秒)
echo "正在測試: $url ..." # 先顯示正在測試的網址
curl_output=$(curl -L -s -o /dev/null --head -w "%{http_code}" --connect-timeout 5 --max-time 10 "$url" 2>&1)
# 檢查 curl_output 是否只包含數字 (狀態碼)
if [[ "$curl_output" =~ ^[0-9]{3}$ ]]; then
http_code="$curl_output"
if [[ "$http_code" -ge 200 && "$http_code" -lt 400 ]]; then
result="通 (狀態碼: $http_code)"
elif [[ "$http_code" == "000" ]]; then
result="不通 (無法連線或請求超時,狀態碼: $http_code)"
else
result="不通 (狀態碼: $http_code)"
fi
else
http_code="N/A"
# 移除 curl 可能輸出的進度百分比等非錯誤訊息
error_message=$(echo "$curl_output" | sed 's/^[[:space:]]*[0-9]\+[^%]*%[[:space:]]*//' | head -n 1)
result="不通 (錯誤: ${error_message:-$curl_output})"
fi
echo "結果: $url - 狀態: $result"
echo "--------------------------------------------------" # 分隔線
}
# 主腳本邏輯
if [ ${#URLS_TO_CHECK[@]} -eq 0 ]; then
echo "錯誤:請在腳本中定義 URLS_TO_CHECK 陣列,並填入至少一個網址。"
exit 1
fi
echo "開始測試腳本中定義的網址..."
echo ""
for url_item in "${URLS_TO_CHECK[@]}"; do
check_url "$url_item"
done
echo ""
echo "所有網址測試完成。"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment