Shell脚本

Shell函数应用

  • 在编写脚本时,有些语句会使用到很多次,为了方便重复使用,可以将代码写成函数,即可做到更高效的重复利用。

语法格式1

name() {
命令序列
}

语法格式2

function name  {
}

示例

[[email protected] ~]# cat Ltools.sh 
#!/bin/bash
HINT()  {
read -p "单击回车继续:"
}

CPU_INFO()  {
echo
echo -e "\033[4;31mCPU信息:\033[0m"
cat /proc/cpuinfo | awk 'BEGIN{FS=":"} /model name/{print "CPU Model:" $2}'
cat /proc/cpuinfo | awk 'BEGIN{FS=":"} /cpu MHz/{print "CPU Speed:" $2}'
grep -Eq 'svm|vmx' /proc/cpuinfo && echo "Vitualization: Support" || echo "Vitualization: Not support"
echo
}

LOAD_INFO() {
echo
echo -e "\033[4;31m系统负载信息:\033[0m"
uptime | awk 'BEGIN{FS=":"}{print $4}' | awk 'BEGIN{FS=","}\
        {print "一分钟内的系统负载:"$1"\n""五分钟内的系统负载:"$2"\n""十五分钟内的系统负载:"$3"\n"}'
echo
}

MEM_INFO()  {
echo 
echo -e "\033[4;31m运行内存和Swap状态:\033[0m"
free | grep Mem | awk '{print "运行内存使用:"$3" Bytes"}'
free | grep Mem |awk '{print "运行内存剩余:"$4" Bytes"}'
free | grep Swap | awk '{print "Swap剩余:"$4" Bytes"}'
echo
}

DISK_INFO()  {
echo 
echo -e "\033[4;31m当前系统磁盘状态:\033[0m"
df -h
echo
}

while true
do
        clear
        echo "------------------------------"
        echo "1.查看CPU信息"
        echo "2.查看系统负载信息"
        echo "3.查看运行内存和Swap状态"
        echo "4.查看当前系统状态"
        echo "5.退出"
        echo "------------------------------"
        read -p "请输入一个数字:" SELECT_NUM
        case $SELECT_NUM in
                1)
        CPU_INFO
        HINT
        ;;
                2)
        LOAD_INFO
        HINT
        ;;
                3)
        MEM_INFO
        HINT
        ;;
                4)
        DISK_INFO
        HINT
        ;;
                5)
        exit
        ;;
                *)
        read -p "请输入合适的数字,按回车继续"
        esac
done