if语句的3种格式
>> 单分支if语句:
if 测试条件;then
代码分支
fi
>> 双分支if语句:
if 测试条件;then
条件为真时执行的分支
else
条件为假时执行的分支
fi
> 多分支if语句:
if CONDITION1; then
条件1为真分支
elif CONDITION2; then
条件2为真分支
elif CONDITION3; then
条件3为真分支
…
elif CONDITIONn; then
条件n为真分支
else
所有条件均不满足时的分支
fi
举例1:多分支if语句
———————
#!/bin/bash if [ $# -lt 1 ]; then echo "at least one pathfile." exit 11 fi if ! [ -e $1]; then echo "no such file." exit 22 fi if [ -f $1 ]; then echo "common file type." elif [ -d $1 ]; then echo "directory file type." elif [ -b $1 ]; then echo "block special file type." elif [ -c $1 ]; then echo "character special file type." elif [ -L $1 ]; then echo "symbolic file type." elif [ -S $1 ]; then echo "socket file type." else echo "unknow file type." fi
举例2:
传递一个参数给脚本,此参数为用户名;根据其ID号判断此用户的类型:0为管理员,1-999为系统用户,1000+为登录用户;
——————————————————————————————————————————————————
#!/bin/bash if [ $# -lt 1 -o $# -ge 2 ]; then echo echo "just need one arg : username." exit 11 fi id $1 &> /dev/null if ! [ $? -eq 0 ]; then echo echo "$1 user is no exits.creating now..." useradd $1 echo echo "add $1 is finishied." else echo echo "$1 user is already exits." echo fi user_id=$(id -u $1) if [ $user_id -eq 0 ]; then echo echo "$1 is root." elif [ $user_id -ge 1 -a $user_id -le 999 ]; then echo echo "$1 is system type user." elif [ $user_id -ge 1000 ]; then echo echo "$1 is common user." else echo echo "cound not konw user." fi
举例3:
列出如下菜单给用户:
disk) show disks info;
mem) show memmory info;
cpu) show cpu info;
*) quit;
提示用户给出自己的选择,而后显示对应其选择的相应系统信息;
—————————————————————————–
#! /bin/bash echo echo -e "disk)show disks info;\nmem)show memory info;\ncpu)show cpu info;\n*)quit;" read -p "choose one option : " option1 if [ $option1 == "disk" ]; then echo fdisk -l elif [ $option1 == "mem" ]; then echo free -m elif [ $option1 == "cpu" ]; then echo cat /proc/cpuinfo else exit fi #上面的: echo -e "disk)show disks info;\nmem)show memory info;\ncpu)show cpu info;\n*)quit;" #可以用下面方式代替: cat << EOF disk)show disks info; mem)show memmory info; cpu)show cpu info; *)quit; EOF