for循环语句

读取不同的变量值,用来逐个执行同一组命令

for 变量名 in 取值列表
do                   
   命令序列
done

遍历

for i in {1..10}
      或 $(seq 1 10)
      或 ((i=1; i<=10; i++))
do
echo $i
done 

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

for i in {1..10..2} 
      或 $(seq 1 2 10)
      或 ((i=1; i<=10; i++))
do
echo $i
done 

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

例题1:批量添加用户

①创建用户名的文件

Shell循环语句及中断语句的使用

②编写脚本

#!/bin/bash
a=$(cat name.txt)
 for i in a
do
 useradd $i
 echo "123456" | passwd --stdin $i
done

Shell循环语句及中断语句的使用

③验证

Shell循环语句及中断语句的使用

例题2:根据IP地址检查主机状态

#!/bin/bash
for i in 192.168.100.{1..20}
do
  ping -c 3 -i 0.5 -W 2 $i &> /dev/null
if [ $? = 0 ]
 then
  echo "$i online"
 else
  echo "$i offline"
fi
done

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

while循环语句

重复测试某个条件,只要条件成立则反复执行

while 条件测试操作
do
   命令序列
done
#!/bin/bash
i=0
while (($i <=10))
do
echo "$i"
let i++
done

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

例题1 猜价格游戏

#!/bin/bash
price=$[$RANDOM % 1000]
a=0
times=0
echo "猜猜商品价格是多少"
while [ $a -eq 0 ]
do
let times++
read -p "请输入你猜的价格:" b
if [ $b -eq $price ];then
  echo "yes!"
  let a++
elif [ $b -gt $price ];then
  echo "你猜大了!"
elif [ $b -lt $price ];then
  echo "你猜小了!"
fi
done
echo "你总共猜了 $times 次"

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

例题二:批量添加用户

#!/bin/bash
i=0
while [ $i -le 4 ]
 do
 let i++
useradd stu$i
 echo "123456" | passwd --stdin stu$i
done

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

until循环语句

重复测试某个条件,只要条件不成立则反复执行

until 条件测试操作
do
   命令序列
done
#显示1-10的整数
#!/bin/bash
i=1
until [ $i -gt 10 ]
do
 echo "$i"
 let i++
done

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

例题:计算1~50的值

#!/bin/bash
i=1
sum=0
until [ $i -gt 50 ]
do
 sum=$(($sum+$i))
 let i++
done
 echo "$sum"

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

中断(break和continue)

①break

break跳出单个循环

#!/bin/bash
for i in {1..5}
do
echo "外层循环 $i"
 for b in {1..5}
 do
 if [ $b -eq 3 ]
  then
  break
 fi
  echo "内层循环 $b"
done
done

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

②continue

continue中止某次循环中的命令,但不会完全中止整个命令

#!/bin/bash
for i in {1..5}
 do
  echo "外层循环 $i"
  for b in {1..5}
 do
 if [ $b -eq 3 ]
  then
  continue
 fi
  echo "内层循环 $b"
 done
done

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

IFS字段分割符

默认包含空格,制表符,换行符

1.修改
IFS=$'\t\n'
修改成只换行
IFS=$'\n'
IFS=':'
IFS=','
2.备份
IFS. OLD=$IFS
IFS=$'\n'
...
IFS=$IFS.OLD

例题:输出环境变量PATH所包含的所有目录以及其中的所有可执行文件

#!/bin/bash
OLDIFS=$IFS
IFS=':'
  for i in $PATH
 do
  for a in $i/*
 do
 if [ -x $a -a -f $a ];then
  echo "$a 文件有执行权限"
 fi
 done
done
IFS=$OLDIFS

Shell循环语句及中断语句的使用

Shell循环语句及中断语句的使用

原文地址:https://blog.csdn.net/weixin_53496478/article/details/114651528

相关文章: