case语句
1.特点:case语句为多重匹配语句;如果匹配成功,执行相匹配的命令
2.语句结构:
case var in
pattern 1)
command 1
;;
pattern 2)
command 2
;;
*)
command 3
;;
esac
练习1:用case语句编写脚本
#!/bin/bash
menu(){
echo "
h 显示命令帮助
f 显示磁盘分区
d 显示磁盘挂载
m 显示内存信息
q 退出程序帮助
"
}
menu
while true
do
read -p “Please input your choice: " choice
case $choice in
h)
menu
;;
f)
echo “#######磁盘分区信息”
blkid | cut -d: -f1
;;
d)
echo “#######磁盘挂载信息”
fdisk -l
;;
m)
echo “#######内存信息”
free -m
;;
q)
echo “#######程序正在退出”
exit
;;
*)
echo “#######请输入正确命令”
esac
done
练习2:判断用户输入的字符串,如果是"hello”,则显示"world";如果是"world", 则显示"hello",否则提示"请输入hello或者world,谢谢!"
练习3:执行users_create.sh userlist passlist达到如下效果:
建立userlist列表中的用户
设定userlist列表中的密码为passlist列表中的密码
当脚本后面跟的文件个数不足两时,报错
当文件行数不一致时报错
当文件不存在时报错
当用户存在时报错
Shell中的循环判断语句(3)case语句,内附练习
#!/bin/bash
[ "$USER" = "root" ] &>/dev/null ||{
echo -e "\033[31mPlease exac super user!!!\033[0m"
exit
}
[ $# -eq 2 ] &>/dev/null ||{
echo -e "\033[31mPlease input userlist and passwdlist!!!\033[0m"
exit
}
[ -e "$1" ] &>/dev/null ||{
echo -e "\033[31mERROR: the userfile is not exist\033[0m"
exit
}
[ -e "$2" ] &>/dev/null ||{
echo -e "\033[31mERROR: the passwdlist is not exist\033[0m"
exit
}
users_line=`wc -l $1 | cut -d" " -f1`
passwd_line=`wc -l $2 | cut -d " " -f1`
[ $users_line -eq $passwd_line ] ||{
echo "ERROR:usersfile lines is differ passwdfile"
exit
}
for num in `seq 1 $users_line`
do
username=`sed -n ${num}p $1`
password=`sed -n ${num}p $2`
useradd $username &>/dev/null
if [ $? = 0 ]
then
echo -e "\033[32muser $username is created!!!\033[0m"
echo $password | passwd --stdin $username &>/dev/null
echo -e "\033[32mThe password is $password !!!\033[0m"
else
echo -e "\033[31m$username is exist!!!\033[0m"
fi
done