Shell介绍(三)if判断,case控制,for循环,while循环,流程控制语句
单分支
if [你有房] then 我就嫁给你 fi
if [ 你有房 ] then 我就嫁给你 else 拜拜 fi
if [ 你有房 ] then 我就嫁给你 elif [ 你有钱 ] then 我也嫁给你 elif [ 你爸是李刚 ] then 我也嫁给你 elif [ 活好!运维技术好 ] then 我倒贴也嫁给你 else 拜拜 fi
案例: 根据操作系统不同的版本安装不同的源
[root@web scripts]# cat yum.sh
#!/bin/sh
ve=`cat /etc/redhat-release |awk '{print $(NF-1)}'`
#centos6.x使用以上命令获取不到版本号
if [ ${ve%%.*} -eq 7 ]
then
#判断网络是否通畅ping 如果不通 则重启systemctl restart network 通继续执行
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
#测试wget是否已安装 无安装先安装wget
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
elif [ ${ve%%.*} -eq 6 ]
then
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
ficase 变量名4 in 模式匹配1) 命令的集合 ;; 模式匹配2) 命令的集合 ;; 模式匹配3) 命令的集合 ;; *)####*的下一行不需要有;; echo USAGE[$0 1|2|3] esac
案例:系统菜单
[root@web scripts]# cat menu.sh
#!/bin/sh
echo -e"\t\t#########################"
echo -e"\t\t#\t1.系统负载\t#"
echo -e"\t\t#\t2.磁盘使用率\t#"
echo -e"\t\t#\t3.内存使用率\t#"
echo -e"\t\t#\t4.当前登录用户\t#"
echo -e"\t\t#\t5.当前eth0的IP\t#"
echo -e"\t\t#\t6.显示菜单\t#"
echo -e"\t\t#########################"
menu(){
cat<<EOF
1.u 系统负载
2.d 磁盘使用率
3.f 内存使用率
4.w 当前登录用户
5.ip 当前eth0的IP
6.h 显示帮助(菜单)
7.q 退出
EOF
}
menu
while true
do
read -p "请输入你想要查看的系统信息的编号: " num
case $num in
1|u)
uptime
;;
2|d)
df -h
;;
3|f)
free -h
;;
4|w)
w
;;
5|ip)
ip add
;;
6|h)
clear
menu
;;
7|q)
exit
;;
*)
menu
esac
donefor循环
for 变量名 in [取值列表] 苹果 香蕉 梨 桃子 西瓜 字符串 数字{}序列 命令
do
命令体
echo 呵呵
done案例: 使用for循环创建用户
[root@web scripts]# cat for1.sh #!/bin/sh for i in `cat user.txt` do useradd $i done
使用for循环 从1加到100 结果5050
for i in `seq 100` do sum=$[sum+i] done echo $sum
while循环
while [ 条件表达式 ] do 命令 done
案例: 1加到100
#!/bin/sh i=0 while [ $i -le 100 ] do sum=$[i+sum] let i++ done echo $sum
流程控制语句 exit continue break
exit 退出整个脚本 不会继续执行
[root@web scripts]# cat exit.sh break.sh continue.sh #!/bin/sh while true do echo ok exit echo hehe done echo done...... #!/bin/sh while true do echo ok break echo hehe done echo done...... #!/bin/sh while true do echo ok continue echo hehe done echo done......
案例2:
#!/bin/sh for i in `seq 10` do user=oldboy$i id $user &>/dev/null if [ $? -ne 0 ];then useradd $user [ $? -eq 0 ] && echo "$user create is ok" else break fi done echo hehe....... #!/bin/sh for i in `seq 10` do user=oldboy$i id $user &>/dev/null if [ $? -ne 0 ];then useradd $user [ $? -eq 0 ] && echo "$user create is ok" else continue fi done echo hehe.......



豫公网安备41042502000209号