1.if语句
-
if单分支语句
统计登录shell为bash的用户
-
if双分支语句
统计uid小于等于500和大于500的用户个数
-
if-else语句
[root@localhost mnt]# vim if-else.sh #!/bin/bash read -p "请输入用户名" user if grep $user /etc/passwd;then echo "The files for user $user are:" ls -a /home/$user else echo "$user not exist!" fi
-
if-elif-else语句
[root@localhost mnt]# vim if-elif-else.sh #!/bin/bash if [ "$1" == "student" ]; then echo "Welcome $1" elif [ "$1" == "westos" ];then echo "Welcome $1" elif [ "$1" == "kiosk" ];then echo "Welcome $1" elif [ $1 == linux ];then echo "Welcome $1" else echo "You are not allowed!" fi
可以用if语句判断文件或设备类型
[root@localhost mnt]# vim file.sh
#!/bin/bash
read -p "请输入要检测的文件或设备" a
if [ -f "$a" ];then
echo "$a是普通文件"
elif [ -b "$a" ];then
echo "$a是块设备"
elif [ -S "$a" ];then
echo "$a是套接字"
elif [ -c "$a" ];then
echo "$a是字符设备"
elif [ -L "$a" ];then
echo "$a是软链接"
else
echo "此文件不存在"
fi
2.for循环语句
练习:ping 其他主机
[root@foundation55 mnt]# vim ping.sh
方法一 #!/bin/bash
for A in `seq 10`
do
ping 172.25.55.$A -c1 >>/dev/null && echo -e "172.25.55.$A is up" || echo -e "172.25.55.$A is down"
done
方法二
#!/bin/bash
for ((A=1;A<10;A++))
do
ping 172.25.254.$A -c1 >>/dev/null && echo 172.25.254.$A up || echo 172.25.254.$A down
done
练习:倒数计时
[root@localhost mnt]# vim time.sh
#!/bin/bash
read -p "请输入分:秒" k j
a=$k*60+$j
for ((b=$a;b>0;b--))
do
echo -n "TIME $[$b/60]:$[$b%60]"
echo -ne "\r"
sleep 1
done
练习:批量建立用户并修改密码为123456
[root@localhost mnt]# vim user.sh
方法一 #!/bin/bash
for A in `seq 10`
do
useradd westos$A
echo "123456" | passwd --stdin westos$A >>/dev/null
done
方法二 #!/bin/bash
a=1
while [ $a -le 20 ]
do
useradd westos$a
echo "123456" | passwd --stdin westos$a
((a++))
done
练习:九九乘法表
[root@localhost mnt]# vim chengfa.sh
#!/bin/bash
for ((a=1;a<10;a++))
do
{
for ((b=1;b<=$a;b++))
do
echo -n " $a*$b=$[$a*$b] "
done
}
echo -e "\n"
done
3. case语句
[root@localhost mnt]# vim case.sh
#!/bin/bash
case $1 in
student|kiosk|linux|westos)
echo "Welcome,$1"
;;
*)
echo "Sorry!"
;;
esac
4.while循环
我们可以通过while语句写一个显示系统下运行时间的脚本
[root@localhost mnt]# vim while.sh
#!/bin/bash
while true
do
uptime
sleep 2
done
练习:做一个交互的操作模式
[root@localhost mnt]# vim xuanze.sh
#!/bin/bash
while true
do
echo -e "
\033[31m A 查看ip \033[0m
\033[32m B 查看剩余空间\033[0m
\033[33m C 查看运行时间\033[0m
\033[34m Q 退出\033[0m
"
read -p "请输入选择:" a
case $a in
A)
echo -e " \033[31m `ifconfig eth0 | grep "netmask"| awk '{print $2}'` \033[0m "
;;
B)
echo -e " \033[32m `df| head -2 |tail -1|awk '{print $4'}` \033[0m "
;;
C)
echo -e " \033[33m `uptime|awk '{print $3}'|awk -F, '{print $1}'| awk -F: '{print "已经开机"$1"时"$2"分"}'` \033[0m "
;;
Q)
exit 1
;;
esac
done