在写shell脚本的时候,可能会需要下载一些文件,这个文件有多个源提供使用。因此,选择最快的源可以大大减少时间,并增加使用体验。于是乎在闲着的时候想出来了这么一个脚本。萌新一个,如果大佬有什么好的建议欢迎留言。
此脚本的用途:配置好源域名,脚本会ping每个域名4次并取平均值,然后返回最快的域名。
复制代码
- #!/bin/bash
- # Server域名或IP地址
- # 例:server[0]="www.baidu.com" server[1]="www.mxin.moe"
- servers=(
- "www.baidu.com"
- "www.mxin.moe"
- "www.qq.com"
- "www.sina.com"
- )
- # 检查操作系统并安装bc
- source /etc/os-release
- case $ID in
- debian|ubuntu)
- sudo apt -y install bc > /dev/null 2>&1
- ;;
- centos)
- sudo yum -y install bc > /dev/null 2>&1
- ;;
- *)
- echo '此脚本不支持此操作系统'
- exit 1
- ;;
- esac
- # 用于存储每个服务器的平均延迟
- declare -A ping_results
- # 测试每个服务器的延迟
- for server in "${servers[@]}"; do
- total_time=0
- for i in {1..4}; do
- # 获取ping的时间,添加错误处理
- ping_time=$(ping -c 1 -W 2 "$server" | awk -F'/' 'END{print $5}')
- if [[ -n "$ping_time" ]]; then
- total_time=$(echo "$total_time + $ping_time" | bc)
- fi
- done
- avg_time=$(echo "scale=2; $total_time / 4" | bc)
- ping_results["$server"]=$avg_time
- done
- # 找到平均延迟最小的服务器
- fastest_server=$(printf "%s\n" "${!ping_results[@]}" | xargs -I {} bash -c 'echo "{} ${ping_results[{}]}"' | sort -n -k2 | head -n1 | awk '{print $1}')
- echo $fastest_server # 此变量为返回的最快域名