【Linux Shell脚本编程】if流程控制与for循环语法介绍

TangLu 未命名 2018-07-11 14883 0

一、if流程控制语句

if语句通常用于条件判断,比如判断主机有没有装某个软件,没有装的话就进行安装,其语法格式如下

#单分支if语句
#写法1:
if  [ 条件判断式 ];then
    所需要执行程序
fi

#写法2:
if  [ 条件判断式 ]
then
    所需要执行程序
fi 


#双分支if语句
#写法1:
if [ 条件判断式 ];then
    所需要执行程序
else
    所需要执行程序 
fi

写法2:
if [ 条件判断式 ]
then
    所需要执行程序
else
    所需执行程序 
fi

#多分支if语法
if  [ 条件判断式1 ];then
  条件判断式1成立时需要执行的程序
elif [ 条件判断式2];then
  条件判断式1不成立但2成立时需要执行的程序
elif  [ 条件判断式3 ];then
条件判断式1和2不成立时需要执行的程序
else
  所有条件判断式都不成立时执行程序
fi


二、for循环

for循环通常用于固定次数的循环,比如创建100个用户,ping100个主机等,其语法格式如下:

for  $var  in  序列列表
do
    所需执行程序
done


for循环要生成序列列表有以下方式:

1、花括号:

for i in {1..100}  #代表1到100的列表

2、引用文件:

for line in `cat ip.txt`

需要注意的是当文件某一行有空格或者tab时,要将IFS变量设置为换行符,否则会从空白处进行换行处理,while语句不会有这个问题

OLDIFS=$IFS
IFS=$'\n'
for i in `cat /etc/passwd`;
do
...
done
IFS=$OLDIFS

3、seq命令:`seq  [起始数]  [步进长度]  结束数`(需要反引号替换):

seq  10:代表生成1到10的列表
seq 5 10:生成5到10的列表
seq 1 2 10:从1开始,步进长度为2,到10终止



for循环示例

计算1到100的合(常见面试题)

[root@localhost ~]# cat  for.sh 
#!/bin/bash
declare -i sum=0
for i in {1..100}
do 
  let sum=$(($sum+$i))
done
echo "sum is $sum "
[root@localhost ~]# ./for.sh 
sum is 5050


批量添加用户,密码同用户名一样,如果用户已经存在则打印用户已存在的提示信息

[root@localhost ~]# cat for.sh 
#!/bin/bash
for i in `cat /userlist`
do
  if ! id $i &>/dev/null 
    then
      useradd $i &>/dev/null 
      echo $i | passwd --stdin $i
    else
      echo "the user is exist"
  fi
done
[root@localhost ~]# ./for.sh     #没有用户的情况下正常建立了用户
Changing password for user user1.
passwd: all authentication tokens updated successfully.
Changing password for user user2.
passwd: all authentication tokens updated successfully.
Changing password for user user3.
passwd: all authentication tokens updated successfully.
[root@localhost ~]# ./for.sh     #已经有用户的情况下提示
the user is exist
the user is exist
the user is exist

评论