读取不同的变量值,用来逐个遍历
for 变量名 in 取值列表
do
命令序列
done
举例:输出1到10的数字
for i in {
1..10}
do
echo $i
done
举例:1到100的和三种方式
sum=0
for i in $(seq 1 100)
do
echo "$[sum+=$i]"
done
sum=0
for ((i=1;i<=100;i++)){
echo "$[sum+=$i]"
}
sum=0
for i in {
1..100}
do
echo "$[sum+=$i]"
done
{
1..10..2} | ${seq 1 2 10} | ((i=0;i<=10;i+=2))
意为1到10,每次进2
for i in {
1..10..2}
do
echo $i
done
for((i=0;i<=10;i++)){
useradd "cat"$i
echo "123456" | passwd --stdin "cat"$i
}
for user in `cat users.txt`
do
useradd $user
echo "123456" | passwd --stdin $user
done
for i in 192.168.1.{
1..10}
do
ping -c 3 -i 0.5 -w 2 $i &> /dev/null
if [ $? -eq 0 ];then
echo "$i online"
else
echo "$i die"
fi
done
for i in 192.168.1.{
1..10}
do
ping -c 3 -i 0.5 -w 2 $i > /dev/null && echo "$i online" > || echo "$i off"
done
首先需要手动给他定义一个初始值,循环的时候需要进行迭代的操作,如果不做可能会出现死循环
while 条件测试操作
do
命令序列
done
举例:输出1到10 注意变量迭代的位置
i=0
while [ $i -le 10 ]
do
echo $i
let i++
done
i=0
while [ $i -lt 10 ]
do
useradd "dog"$i
echo 123 | passwd --stdin "dog"$i
let i++ 或 i=[$i+1]
done
此处使用变量$RANDOM
大小区间为 0 ~ 65535
a=$[$RANDOM % 10]
b=0
c=0
while [ $b -lt 1 ]
do
let c++
read -p "请输入你要猜的数: " d
if [ $d -lt $a ];then
echo "你猜小了"
elif [ $d -gt $a ] ;then
echo "你猜大了"
elif [ $d -eq $a ];then
echo "恭喜你猜对了,它的数是$a,你一共猜了$c次!!"
fi
done
重复测试某个条件,只要条件不成立则反复执行
until 条件测试操作
do
命令序列
done
sum=0
i=0
until [ $i -gt 100 ]
do
let sum=$sum+$i
let i++
done
echo $sum
#!/bin/bash
for ((i=1;i<=5;i++)){
for ((j=1;j<=5;j++)){
echo -n "*"
}
echo ""
#!/bin/bash
for ((i=1;i<=10;i++)){
for ((j=1;j<=i;j++)){
echo -n "*"
}
echo ""
}
#!/bin/bash
for ((i=1;i<=10;i++)){
for ((j=10;j>=i;j--)){
echo -n "*"
}
echo ""
}
#!/bin/bash
for ((i=1;i<=10;i++)){
for ((j=10;j>=i;j--)){
echo -n " "
}
x=$[ (i * 2)-1 ]
for ((k=1;k<=x;k++)){
echo -n "*"
}
echo ""
}
#!/bin/bash
for ((i=1;i<=11;i++)){
for ((j=1;j<=i;j++)){
echo -n " "
}
for ((k=11;k>=i;k--)){
echo -n "*"
}
for ((x=10;x>=i;x--)){
echo -n "*"
}
echo ""
}
#!/bin/bash
for ((i=1;i<=12;i++)){
for ((j=11;j>=i;j--)){
echo -n " "
}
x=$[ ($i * 2)-1 ]
for ((k=1;k<=x;k++)){
echo -n "*"
}
echo ""
}
for ((i=1;i<=11;i++)){
for ((j=1;j<=i;j++)){
echo -n " "
}
for ((k=11;k>=i;k--)){
echo -n "*"
}
#!/bin/bash
for ((i=1;i<=12;i++)){
for ((j=11;j>=i;j--)){
echo -n " "
}
x=$[ ($i * 2)-1 ]
for ((k=1;k<=x;k++)){
echo -n "*"
}
echo ""
}
for ((a=1;a<=8;a++)){
for ((b=1;b<=8;b++)){
echo -n " "
}
for ((c=1;c<=3;c++)){
for ((d=1;d<=2;d++)){
echo -n "*"
}
}
echo ""
}
for ((i=1;i<=11;i++)){
for ((j=1;j<=i;j++)){
echo -n " "
}
for ((k=11;k>=i;k--)){
echo -n "*"
}