Shell循环语句及中断语句的使用(shellwhile循环)满满干货

随心笔谈11个月前发布 admin
89 0



目录for循环语句例题1:批量添加用户例题2:根据IP地址检查主机状态while循环语句例题1 猜价格游戏例题二:批量添加用户until循环语句例题:计算1~50的值中断(break和continue)①break②continueIFS字段分割符

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

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

遍历

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

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

①创建用户名的文件

②编写脚本

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

③验证

#!/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

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

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

#!/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 次”

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

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

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

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

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

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

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

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循环语句及中断语句内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:shell编程中for循环语句的实现过程及案例shell脚本实战-while循环语句shell脚本编程之循环语句shell中的循环语句、判断语句实例Shell脚本for循环语句简明教程Shell中的循环语句for、while、until实例讲解

© 版权声明

相关文章