#!/bin/bash#常见判断apacha进程是否启动:#ps aux | grep httpd#弊端:有些情况下能判断apache启动了,但是她不能解决apache启动但电脑死机的情况,即apache无法响应后端请求。#netstat -tlun#弊端:不能确定apache是不是正常连接,只能确定是不是启动了;且不一定是apache占用的80端口,其他的网页服务,rs等也有可能占用#nmap是扫描指定服务器上开启的tcp端口#使用nmap命令扫描服务器并截取apache服务的状态,赋予变量port#下面的语句意思:截取tcp端口状态,再从输出的状态中截取apache状态
port=$(nmap - sT 192.168.1.156 | grep tcp | grep http |awk '{print $2}')#注意必须有空格if["$port" == "open"]
then
echo"$(date) httpd is ok!" >> /tmp/autostart-acc.log
else/etc/rc.d/init.d/http start &>/dev/null
echo"$(date) restart http !!" >> /tmp/autostart-err.log
fi
需求4:判断用户输入的是什么文件
#!/bin/bash#接收键盘的输入,并赋予变量file
read -p "Please input a filename:" file
#判断file变量是否为空if[-z "$file"]
then
echo"Error,please input a filename"#如果不写exis就会继续往下运行exit 1
#判断file的值是否存在
elif [!-e "$file"]
then
echo"$file is not a file!"exit 2
#判断file是否为普通文件
elif [-f "$file"]
then
echo"$file is a regulare file!"#判断file是否为目录文件
elif [-d "$file"]
then
echo"$file is a directory!"elseecho"$file is an other file!"
fi
需求5:判断用户输入
#!/bin/bash
read -p "Please choose yes/no:"-t 30 cho
case $cho in
"yes")echo"Your choice is yes!";;"no")echo"Your choice is no!";;*)echo"Your input is error!";;
esac
需求6:打印时间
#!/bin/bashfor time in morning noon afternoon evening
doecho"This time is $time!"
done
需求7:批量解压缩脚本
#!/bin/bash#假设所有的脚本包都在根下lamp文件中
cd /lamp
#把所有.tar.gz结尾的文件名写入ls.log文件ls*.tar.gz > ls.log
#只要是空格或者换行符隔开的,就认为是一个内容for i in $(catls.log)do
tar -zxf $i &>/dev/null
done
rm-rf /lamp/ls.log
需求8:从1加到100(for)
#!/bin/bash
s=0
for((i=1;i<=100;i=i+1))do
s=$(($s+$i))
done
echo"The sum of 1+2+...+100 is:$s"
需求9:批量添加指定数量的用户
#!/bin/bash#初始用户名#每次添加,在用户名前加一个标号
read -p "Please input user name:"-t 30 name
#添加个数
read -p "Please input the number of users:"-t 30 num
#初始密码
read -p "Please input the password of users:"-t 30 pass
#预期结果是stu01、stu02...if[!-z "$name"-a !-z "$num"-a !-z "$pass"]
then
#判断是否输入的是数字,通过正则匹配#除了以下的正则,还可以是:^[0-9]*$#如果是数字,y就为空
y=$(echo$num| sed 's/[0-9]//g')if[-z "&y"]
then
for((i=1;i<=$num;i=i+1))do/usr/sbin/useradd $name$i &>/dev/null
echo$pass|/usr/bin/passwd --stdin “$name$i” &>/dev/null
done
fi
fi
需求10:从1加到100(while)
#!/bin/bash
s=0
i=1
while[$i-le 100 ]do
s=$(($s+$i))
i=$(($i+1 ))
done
echo"The sum of 1+2+...+100 is:$s"
需求10:从1加到100(until)
#!/bin/bash
s=0
i=1
until[$i-gt 100 ]do
s=$(($s+$i))
i=$(($i+1 ))
done
echo"The sum of 1+2+...+100 is:$s"