shell 学习之脚本编写1

Posted 真坤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell 学习之脚本编写1相关的知识,希望对你有一定的参考价值。

脚本要求:

执行脚本后

   接受输入1,显示当前时间,并提示是否继续选择。

   接受输入2,显示CPU负载,并提示是否继续选择。

   接受输入3,显示剩余内存,并提示是否继续选择。

   接受输入0,退出脚本。

·····················································································································

思路:

  显示当前时间

[root@wk ~]# date +%T
08:26:04

················································································································································································································

uptime命令能显示1)当前系统时间;

        2)本机已经运行时间;

        3)当前系统有几个用户连接;

        4)本机最近1分钟、5分钟、15分钟系统的平均负载。

如下:

 

我们可以将uptime的输出结果用awk来进行选择输出。

····················································································································································································································

free -m 命令能以M为单位显示内存使用情况,还有交换分区swap的使用情况 ,可用awk打印出Mem行第4列的信息,即是我们要的信息。

······················································································································································································································

至于提示是否继续选择,可以用while循环。最终脚本如下:

 1 #!/bin/bash
 2 #
 3 while [ "1" == "1" ]
 4 do
 5     clear
 6     echo "~~~~~~~~~~~~~~~~~~~menu~~~~~~~~~~~~~~~~~~~~~~"
 7     echo "              1) Time Now                    "
 8     echo "              2) CPU Load                    "
 9     echo "              3) Memory Free                 "
10     echo "              0) Exit                        "  
11     echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
12     echo "Please enter a chose[0~3]:"
13     read NUM
14     case ${NUM} in
15       1) echo "Time Now :`date +%T`" ;;
16       2) echo "CPU Load :`uptime |awk -F\'[:,]\' \'{print $6}\'`" ;;
17       3) echo "Memory Free :`free -m |awk \'$1=="Mem:" {print $4}\'`m" ;;
18       0) exit ;;
19       *) echo "This chose is not in [0~3]." 
20     esac
21     echo -n "Do you continue [y/n]:"
22     read continue
23     if [ "${contiune}" == "n" -o "${continue}" == "N" ]
24     then
25            exit
26     fi
27 done

 

以上是关于shell 学习之脚本编写1的主要内容,如果未能解决你的问题,请参考以下文章

Linux学习之二十一-shell编程基础

Shell脚本学习之sed详解

shell脚本学习之实例列举

学习之shell脚本

shell 脚本学习之内部变量

1.shell学习之常用语句