Shell 常用的函数
一、判断
判断是否为 URL 的函数
# 判断是否为 URL 的函数
check_is_url() {
local url="$1"
# 正则表达式匹配 URL
if [[ "$url" =~ ^https?://[^[:space:]]+ ]]; then
return 0 # 是 URL
else
return 1 # 不是 URL
fi
}
判断是否
check_is_command() {
command -v "$1" >/dev/null 2>&1
}
判断是否为中国网络
check_in_china() {
if [ "$(curl -s -m 3 -o /dev/null -w "%{http_code}" https://www.google.com)" != "200" ]; then
return 0 # 中国网络
fi
return 1 # 非中国网络
}
判断网址是否能够联通
check_url_connection() {
_url="${1:-}"
if [[ -z "$_url" ]]; then
return 1
fi
_check_url=$(echo "$_url" | cut -d '/' -f 1-3)
if [[ $(curl -s -m 3 -o /dev/null -w "%{http_code}" "$_check_url") != "200" ]]; then
return 0 # 联通
fi
return 1 # 不能联通
}
判断文件是否为 JSON
check_is_json() {
if file --mime-type "$1" | grep -q 'application/json'; then
if jq empty "$1" >/dev/null 2>&1; then
return 0
else
return 1
fi
else
return 2
fi
}
二、获取
URL 转义函数
get_escape() {
local input="$1"
local escaped=""
# 遍历输入字符串中的每一个字符
for (( i=0; i<${#input}; i++ )); do
char="${input:$i:1}"
# 检查字符是否需要转义
case "$char" in
# 保留字符无需转义 (RFC 3986)
[A-Za-z0-9-_.~])
escaped+="$char"
;;
# 其他字符进行转义
*)
# 将字符转换为 ASCII 十六进制形式
hex=$(printf "%02X" "'$char")
escaped+="%$hex"
;;
esac
done
echo "$escaped"
}
获取系统类型
get_system_info() {
if [ -f /etc/os-release ]; then
# shellcheck source=/dev/null
source /etc/os-release
if [[ "$ID" == "debian" || "$ID" == "ubuntu" || "$ID" == "deepin" ]]; then
echo "debian"
elif [[ "$ID" == "centos" || "$ID" == "fedora" || "$ID" == "redhat" ]]; then
echo "redhat"
else
echo "unknown"
fi
elif [ -f /etc/debian_version ]; then
echo "debian"
elif [ -f /etc/redhat-release ]; then
echo "redhat"
else
echo "unknown"
fi
}
用来判断加速网址是否保留原网址的 https://
(此脚本自用)
# 若为 https://xxx.xx 不以 / 结尾,则组合时去掉加速网址的 https://
# 格式为 https://file.xxx.io/github.com/
# 若为 https://xxx.xx/ 以 / 结尾,则组合时保留加速网址的 https://
# 格式为 https://xxx.xx/https://github.com/
check_remove_https() {
if [[ -n "$1" && "${1: -1}" != "/" ]]; then
echo 1
fi
}
保持最末只有一个斜杠
# 保持最末只有一个斜杠
keep_a_slash() {
echo "$1" | sed -E 's#/*$#/#'
}
删除内容中网址的第二个 https
(此脚本自用)
# 删除内容中网址的第二个 https
remove_second_https() {
# shellcheck disable=SC2001
echo "$1" | sed 's|\(https://[^/]\+\)/https://|\1/|g'
}
替换 GitHub 加速网址
(此脚本自用)
replace_github() {
echo "$1" | sed -e "s#https://github.com#//${CDN}https://github.com#g" \
-e "s#https://api.github.com#//${CDN}https://api.github.com#g" \
-e "s#https://gist.github.com#//${CDN}https://gist.github.com#g" \
-e "s#https://raw.githubusercontent.com#//${CDN}https://raw.githubusercontent.com#g"
}