case statement
1. Features: The case statement is a multiple matching statement; if the matching is successful, execute the matching command
2. Statement structure:
case var in
pattern 1)
command 1
;;
pattern 2)
command 2
;;
*)
command 3
;;
esac
Exercise 1: Use case statements to write scripts
#!/bin/bash
menu(){ echo " h Display command help f Display disk partition d Display disk mounting m Display memory information q Exit program help " }
menu
while true
do
read -p "Please input your choice: "choice
case $choice in
h)
menu
;;
f)
echo "#######Disk partition information"
blkid | cut -d: -f1
;;
d )
echo “#######disk mount information”
fdisk -l
;;
m)
echo “#######Memory information”
free -m
;;
q)
echo “####### The program is exiting"
exit
;;
*)
echo "#######Please enter the correct command"
esac
done
Exercise 2: Determine the string entered by the user, if it is "hello", then display "world"; if it is " world", it will display "hello", otherwise it will prompt "please enter hello or world, thank you!"
Exercise 3: Execute users_create.sh userlist passlist to achieve the following effect:
create users in the
userlist list and set the password in the userlist list to the password in the passlist list.
When the number of files following the script is less than two, an error is reported
when the number of file lines is inconsistent
Report an error when the file does not exist. Report an error
when the user exists
. Loop judgment statements in the Shell (3) case statement with exercises included
#!/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