If-then结构控制的分类:
(1)单分支if结构,此类分支结构,当条件满足时就会执行then后面的语句,不满足就直接退出判断语句
if [条件];then
语句...
fi
程序演练:
Shell实例1:
[root@ChangerLee 顺序结构]# cat id_ifthen_dan.sh
#!/bin/bash
#if_then单分支控制结构演练
id $1
if [ $? -eq 0 ]
then
echo "$1 user exists!"
fi
[root@ChangerLee 顺序结构]# sh id_ifthen_dan.sh apachedid: apached: no such user
[root@ChangerLee 顺序结构]# sh id_ifthen_dan.sh apache
uid=48(apache) gid=48(apache) groups=48(apache)
apache user exists!
(2)双分支结构,当条件满足时就会运行then后面的语句,当条件不满足就会运行else后面的语句
if [条件];then
语句...
else
语句
fi
程序演练:判断第一个系统参数所所赋的用户名是否存在,存在则输出用户UID,否则创建该用户,并且输出这个用户的UID
Shell实例2:
[root@ChangerLee 顺序结构]# cat id_ifthen_double.sh
#!/bin/bash
#if-then双分支演练结构
#id useradd
id=$(id -u $1)
if [ $? -eq 0 ]
then
echo "$1 user already exist,uid is $id"
else
useradd $1
id=$(id -u $1)
echo "$1 is created,and uid is $id"
fi
[root@ChangerLee 顺序结构]# sh id_ifthen_double.sh apache
apache user already exist,uid is 48
(3)嵌套if结构,当条件满足条件1,则执行then后面的语句,当条件再满足条件2,则执行then后面的语句,不满足条件二则执行else语句;当条件不满足条件1,则执行外层else后面的语句
if [条件1];then
if [条件2];then
语句
else
语句
fi
else
语句
fi
Shell实例3:
[root@ChangerLee 顺序结构]# cat id_qianru.sh
#!/bin/bash
#if-then嵌入式程序演练
if [ $# -eq 1 ]
then
id=$(id -u $1)
if [ $? -eq 0 ]
then
echo "$1 user is exist,and id is $id"
else
useradd $1
id=$(id -u $1)
echo "$1 user is already created,and id is $id"
fi
else
echo "error: need one username!!!"
fi
[root@ChangerLee 顺序结构]# sh id_qianru.sh apache
apache user is exist,and id is 48
[root@ChangerLee 顺序结构]# sh id_qianru.sh asd
id: asd: no such user
asd user is already created,and id is 1003
[root@ChangerLee 顺序结构]# sh id_qianru.sh asd apache
error: need one username!!!