shell脚本实践(一)

1、找出长度小于5的单词
for str1 in I am CSDN, I teach you to learn linux.
    do
        if [ `expr length $str1` -lt 5 ]
            then
                echo $str1
        fi
done
2、bc案例:计算1~100的总和
# tr命令替换
echo {1..100} | tr " " "+"

# -s 指定+号为分隔符
seq -s "+" 100

# 计算
# bc命令
seq -s "+" 100 | bc
# 双括号计算
echo $((`seq -s "+" 100`))
# expr计算
seq -s " + " 100 | xargs expr

# awk计算
echo "1 2" | awk '{print {$1+$2)}' # 3

3、逻辑判断脚本

#!/bin/bash

read -p "please input a char:" var1

# 逻辑条件测试
[ "$var1" -eq "1" ] && {
  echo $var1
  exit 0
}
[ "$var1" -eq "2" ] && {
  echo $var1
  exit 0
}

# 只能输入的是1或2, 否则就报错
[ "$var1" != "2" -a "$var1" != "1" ] && {
  echo "脚本出错,必须输入1或2"
  exit 1
}

4、内存监测脚本

#!/bin/bash
# free_check.sh
FreeMem=`free -m | awk 'NR==2 {print $NF}' `
CHARS="Current memory is $FreeMem"
if [ "$FreeMem" -lt "100" ]
  then
    echo $CHARS|tee /tmp/messages.txt
    # mail -s "主题" 收件人 <
    mail -s "`date +%F-%T`$CHARS" [email protected] < /tmp/messages.txt
    echo "内存不足,抓紧维护服务器"
fi
# 执行脚本
bash free_check.sh


# 加入定时任务
# crontab -l
# 3分钟执行一次
*/3 * * * * /bin/bash /shell/free_check.sh &>/dev/null

5、mysql监控脚本

#用于显示 tcp,udp 的端口和进程等相关情况
netstat 查看端口占用语法格式:

netstat -tunlp | grep 端口号
-t (tcp) 仅显示tcp相关选项
-u (udp)仅显示udp相关选项
-n 拒绝显示别名,能显示数字的全部转化为数字
-l 仅列出在Listen(监听)的服务状态
-p 显示建立相关链接的程序名

if [ `netstat -tunlp | grep mysql | wc -l` -ge "1" ]
then
  echo "Mysql is running!"
else
  echo "Mysql is not running!
  systemctl start mysql
fi


shell脚本实践(一)_第1张图片

6、rsync脚本开发

# 限制用户传入一个参数   -ne 不等于
if [ "$#" -ne 1 ]
  then
    echo "Usage: $0 {start|stop|restart}"
    exit 1
fi

if [ "$1" = "start" ]
  then
    /user/bin/rsync --daemon
    sleep 2
    # 验证端口是否启动了 -ge:大于等于
    if [ `netstat -tunlp | greo rsync | wc -l` -ge 1 ]
    then
      echo "Rsync is started!"
      exit 0
    fi
elif [ "$1" = "stop" ]
  then
    killall rsync &>/den/null
    sleep 2
    if [ `netstat -tunlp | greo rsync | wc -l` -eq 0 ]
    then
      echo "Rsync is stoped!"
      exit 0
    fi
elif [ "$1" = "restart" ]
  then
    killall rsync &>/den/null
    sleep 1
    killpro=`netstat -tunlp | greo rsync | wc -l`
    /user/bin/rsync --daemon
    killpro=`netstat -tunlp | greo rsync | wc -l`
    sleep 1
    startpro=`netstat -tunlp | greo rsync | wc -l`
    if [ "$killpro" -eq  -a "$startpro" -ge 1 ]
    then
      echo "Rsync is restarted!"
      exit 0
    fi
else
  echo "Usage: $0 {start|stop|restart}"
  exit 1
fi


【Shell编程】-基础(一)
【shell编程】父子shell和特殊变量
【shell编程】-条件判断
【shell编程】特殊命令用法

你可能感兴趣的:(bash,linux,运维,运维开发,笔记,课程设计,经验分享)