常用Shell方法集合

判断是否是root用户

1
2
3
4
5
6
7
8
9
10
check_root() {
local user=""
user="$(id -un 2>/dev/null || true)"
if [ "$user" != "root" ]; then
cat >&2 <<-'EOF'
权限错误, 请使用 root 用户运行此脚本!
EOF
exit 1
fi
}

判断命令是否存在

1
2
3
4
5
6
7
8
9
10
command_exists() {
command -v "$@" >/dev/null 2>&1
}
if command_exists ip;then
echo "存在ip命令"
elif command_exists ifconfig; then
echo "存在ifconfig命令"
else
echo "都不存在"
fi

判断参数是否为数字

1
2
3
4
5
6
7
8
9
is_number() {
expr "$1" + 1 >/dev/null 2>&1
}
if ! ( is_number "$1" ); then
cat >&2 <<-EOF
请输入数字
EOF
exit 1
fi

获取服务器IP地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
get_server_ip() {
local server_ip=""
local interface_info=""

if command_exists ip; then
interface_info="$(ip addr)"
elif command_exists ifconfig; then
interface_info="$(ifconfig)"
fi

server_ip=$(echo "$interface_info" | \
grep -oE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | \
grep -vE "^192\.168|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-2]\.|^10\.|^127\.|^255\.|^0\." | \
head -n 1)

# 自动获取失败时,通过网站提供的 API 获取外网地址
if [ -z "$server_ip" ]; then
server_ip="$(wget -qO- --no-check-certificate https://ipv4.icanhazip.com)"
fi

echo "$server_ip"
}

下载文件,重试3次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
download_file() {
# 文件下载链接
local url="$1"
# 文件下载后存放路径
local file="$2"
local retry=0

download_file_to_path() {
if [ $retry -ge 3 ]; then
rm -f "$file"
cat >&2 <<-EOF
文件下载失败! 请重试。
URL: ${url}
EOF
fi

( set -x; wget -O "$file" --no-check-certificate "$url" )
if [ "$?" != "0" ] || [ -n "$verify_cmd" ] && ! verify_file; then
retry=$(expr $retry + 1)
download_file_to_path
fi
}
download_file_to_path
}

# 使用
DOCKERFILE_DOWNLOAD_URL="https://github.com/pibigstar/go-todo/blob/master/Dockerfile"
download_file "$DOCKERFILE_DOWNLOAD_URL" "/usr/local/todo"
-------------本文结束感谢您的阅读-------------