ケースステートメント
1.機能:caseステートメントは複数の一致するステートメントです。一致が成功した場合は、matchingコマンドを実行します。
2.ステートメント構造:
case var in
pattern 1)
command 1
;;
pattern 2)
command 2
;;
*)
command 3
;;
esac
演習1:ケースステートメントを使用してスクリプトを作成する
#!/ bin / bash
menu(){ echo " h表示コマンドヘルプfディスクパーティションの表示dディスクマウントの表示mメモリ情報の表示qプログラムヘルプの終了" }
menu
while true
do
read -p "選択内容を入力してください:" 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“ #######プログラムは終了しています "
exit
;;
*)
echo" #######正しいコマンドを入力してください "
esac
done
演習2:ユーザーが入力した文字列を判別し、「hello」の場合は「world」を表示し、「 「world」の場合は「hello」と表示され、それ以外の場合は「helloまたはworldを入力してください。ありがとうございます」と表示されます。
演習3:users_create.sh userlist passlistを実行して、次の効果を実現します。userlistリストに
ユーザーを作成し、
userlistリストのパスワードをpasslistリストのパスワードに設定します。
スクリプトに続くファイルの数が2未満の
場合、ファイルの行数に一貫性がないとエラーが報告されます。エラーが報告されている場合
、ファイルが存在しない場合、エラーが報告され
、ユーザが存在する場合
。含ま演習とシェル(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