常用Shell方法集合 发表于 2019-08-29 | 分类于 shell 判断是否是root用户12345678910check_root() { local user="" user="$(id -un 2>/dev/null || true)" if [ "$user" != "root" ]; then cat >&2 <<-'EOF' 权限错误, 请使用 root 用户运行此脚本! EOF exit 1 fi} 判断命令是否存在12345678910command_exists() { command -v "$@" >/dev/null 2>&1}if command_exists ip;then echo "存在ip命令"elif command_exists ifconfig; then echo "存在ifconfig命令"else echo "都不存在"fi 判断参数是否为数字123456789is_number() { expr "$1" + 1 >/dev/null 2>&1}if ! ( is_number "$1" ); thencat >&2 <<-EOF请输入数字EOFexit 1fi 获取服务器IP地址12345678910111213141516171819202122get_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次12345678910111213141516171819202122232425262728download_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" -------------本文结束感谢您的阅读-------------