wendu 发表于 2018-8-17 08:19:25

第一个Shell Script

  最近一直在看shell方面的资料,很乏味,也不知道看的效果,正好下午Linux群里一兄弟,提出了一个他们公司的需求,听了之后有点思绪,感觉应该可以写出来,个人的第一个Script就诞生...
  需求:每天登陆服务器查看磁盘空间比较麻烦,所以就想利用一个脚本,用来检测系统磁盘空间,然后将结果通过邮件的形式发送到指定邮箱。
  Script内容如下:
  


[*]#!/bin/bash
[*]#2012/09/17   by Song
[*]#Email:XXX@163.com
[*]
[*]DiskNum=`df -h | grep sda1 | awk '{print $5}' | awk -F "%" '{print $1}'`
[*]Disklog="/tmp/log.txt"
[*]df -hT | grep sda1 >>$Disklog
[*]if [ "$DiskNum"-gt 10 ]; then
[*]   mail -s &quot;Waring:Disk is Full!&quot; XXX@163.com < &quot;$Disklog&quot;
[*]else
[*]   mail -s &quot;Disk is Good!&quot; XXX@163.com < &quot;$Disklog&quot;
[*]fi
  

  提出需求的内位兄弟,简称 咖啡兄弟,也琢磨出了一个脚本,在其他功能方面也比我的完善很多,如下:
  


[*]#!/bin/sh
[*]#2012/09/17   bykukafei
[*]#Email:XX@163.com
[*]
[*]
[*]ip=`ifconfig|grep 192.168|awk '{print $2}'|sed 's/addr://g'`;
[*]time=`date +%F-%H:%M`;
[*]mail_address=&quot;XX@163.com&quot;;
[*]tmpfile=/tmp/check-disk.tmp
[*]a=`df -h | grep 'sda1'|awk '{print int($5)}'`;
[*]
[*]echo &quot;From :$ip&quot; >$tmpfile
[*]echo &quot;DateTime:$time&quot; >> $tmpfile
[*]echo &quot;Info :aimer-sa-wangwei&quot; >> $tmpfile
[*]echo &quot;disk_status_use%=$a&quot; >> $tmpfile
[*]    if [[ &quot;$a&quot; -gt 20 ]]; then
[*]         /bin/mail -s &quot;warning ! $HOSTNAME disk is full !&quot; $mail_address < $tmpfile
[*]    else
[*]         /bin/mail -s &quot;$HOSTNAME disk is ok !&quot; $mail_address < $tmpfile
[*]    fi
  

  咖啡兄弟的脚本主要体现在接收报警邮件的内容方面很具体,可以看到报警的机器IP、主机名、时间、操作人和磁盘空间,而我的只是看到一个磁盘空间而已。
  通过今天的Script,感觉学习shell光看书是没有用的,要多实战才行。
  学习shell要四有:首先要有需求 其次要有思路 然后要有方法 最后要有行动!
  shell学习中,有什么不对的地方,还请大家多多提出。


页: [1]
查看完整版本: 第一个Shell Script