ydswin

忘记背后,努力面前的,向着标杆直跑

导航

shell脚本中常用的自定义函数

在Shell脚本中,你可以定义各种函数来执行不同的任务。以下是20个常用的自定义函数示例,涵盖了从文件操作、文本处理到系统监控等多个方面:

  1. 检查文件是否存在
file_exists() {  
    [ -f "$1" ] && echo "File exists." || echo "File does not exist."  
}
  1. 检查目录是否存在
dir_exists() {  
    [ -d "$1" ] && echo "Directory exists." || echo "Directory does not exist."  
}
  1. 获取文件大小
get_file_size() {  
    du -sh "$1" 2>/dev/null | cut -f1  
}
  1. 列出目录中的所有文件
list_files() {  
    find "$1" -maxdepth 1 -type f -print  
}
  1. 检查命令是否可用
command_exists() {  
    command -v "$1" >/dev/null 2>&1  
}
  1. 获取当前日期
current_date() {  
    date +"%Y-%m-%d"  
}
  1. 获取当前时间
current_time() {  
    date +"%H:%M:%S"  
}
  1. 计算两个日期的差值
date_diff() {  
    date -d "$2" +%s -d "$1" +%s | awk '{print $1 - $2}' | xargs -I {} date -d @-{} +%jd  
}
  1. 打印彩色文本
print_color() {  
    local text=$1  
    local color=$2  
    case "$color" in  
        red)  
            echo -e "\033[31m$text\033[0m"  
            ;;  
        green)  
            echo -e "\033[32m$text\033[0m"  
            ;;  
        yellow)  
            echo -e "\033[33m$text\033[0m"  
            ;;  
        blue)  
            echo -e "\033[34m$text\033[0m"  
            ;;  
        *)  
            echo "$text"  
            ;;  
    esac  
}
  1. 延时执行
delay() {  
    sleep "$1"  
}
  1. 检查是否是root用户
is_root() {  
    [ "$(id -u)" -eq 0 ] && echo "Root user" || echo "Not root user"  
}
  1. 获取IP地址
get_ip() {  
    hostname -I | awk '{print $1}'  
}
  1. 生成随机字符串
generate_random_string() {  
    cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1  
}
  1. 检查端口是否占用
is_port_open() {  
    nc -zv "$1" 2>/dev/null | grep -q open  
}
  1. 重启服务
restart_service() {  
    systemctl restart "$1"  
}
  1. 检查服务状态
service_status() {  
    systemctl is-active --quiet "$1"  
}
  1. 获取最后修改的文件
last_modified_file() {  
    ls -t | head -n 1  
}
  1. 计算目录中文件的数量
count_files() {  
    find "$1" -type f | wc -l  
}
  1. 清空文件内容
empty_file() {  
    > "$1"  
}
  1. 发送邮件
send_email() {  
    echo "$2" | mail -s "$1" "$3"  
}

请注意,这些函数可能需要根据你的具体环境和需求进行调整。例如,发送邮件的函数依赖于系统上的mail命令,而该命令的配置和使用可能因系统而异。同样,检查服务状态和使用systemctl的函数适用于使用systemd的系统。在不支持这些工具的系统上,你需要使用不同的命令或方法来实现相同的功能。

posted on 2024-03-04 00:47  dashery  阅读(131)  评论(0编辑  收藏  举报