一、前言
shell编程中if和case都是用来做流控的。
二、case语法结构
三、简单的模式匹配
需求:邀请用户输入待删除用户名。 询问用户,确定要继续删除吗yes/no:“yes” 。
if写法:
- [root@localhost ~]# vim if.sh #脚本编写
- #!/bin/bash
- #1请输入删除的用户名:
- read -p "please input a username:" user
-
- #2请用户确认是否删除
- read -p "are you sure?[y/n]:" action
- if [ "$action" = "y" -o "$action" = "Y" ];then
- userdel -r $user
- echo "$user is deleted!"
- else
- echo "thank you"
- fi
-
- [root@localhost ~]# bash if.sh #执行脚本
- please input a username:aa
- are you sure?[y/n]:y
- aa is deleted!
case写法:
- [root@localhost ~]# vim case.sh #脚本编写
- #!/bin/bash
- read -p "请输入需要删除的用户名:" user
-
- read -p "请确认删除:[yes/no ]" action
-
- case $action in
- yes|YES|y|Y|Yes|YEs)
- echo "用户同意删除"
- ;;
- no)
- echo "用户取消删除"
- ;;
- esac
-
- [root@localhost ~]# bash case.sh #执行脚本
- 请输入需要删除的用户名:abc
- 请确认删除:[yes/no ]Yes
- 用户同意删除