1.type for
for is a shell keyword
for循环也是关键字,不能单独使用
2.cat for.sh
#!/bin/bash
for i;do
echo i=$i
done
bash for.sh a b c d
i=a
i=b
i=c
i=d
3.面试:用for循环写1到100的和
#!/bin/bash
sum=0
for i in {1..100};do
let sum+=i
done
echo sum=$sum
4.1)用for循环打出6个*在一行
#!/bin/bash
for i in {1..6};do
echo -e '*\c' #这里的e是开启转义,\c是不换行
done
2)用for循环打出6×6*
#!/bin/bash
for j in {1..6};do
for i in {1..6};do
echo -e '*\c'
echo #这里换一行
done
done
3)用for循环打出三角形*
#!/bin/bash
for j in {1..6};do
for i in `seq $j`;do
echo -e '*\c'
done
echo
done
5.用for循环打出99乘法表
#!/bin/bash
for j in {1..9};do
for i in `seq $j`;do
echo -e "\E[1;$[RANDOM%7+31]m${i}x${j}=$[i*j]\E[0m\t\c"
done
echo
done
6.用for循环的第二种语法写1到100的和
#!/bin/bash
for ((i=1;i<=100;i++));do
let sum+=i
done
echo sum=$sum
7.用第二种语法写99
#!/bin/bash
for ((i=1;i<=100;i++));do
for((j=1;j<i;j++));do
echo -e "\E[1;$[RANDOM%7+31]m${i}x${j}=$[i*j]\E[0m\t\c"
done
printf "\n"
done
8.date +%F
2022-02-02
9.循环的执行介绍
将某代码段重复运行多次,通常有进入循环的条件和退出循环的条件
重复运行的次数
*循环次数事先已知
*循环次数事先未知
常见的循环命令:for while until
10.for ((exp1;exp2;exp3));do CMD3;done
11.printf的用法
12.面试:批量创建用户并设置随机密码
#!/bin/bash
for i in {1..10};do
usradd user$i
PASS=`cat /dev/urandom | tr -dc '[:alnum:]' | head -c12`
echo user$i:$PASS --stain user$i &> /data/user.log
echo "user is created"
done
13.面试:将指定目录下的文件的所有后缀改名为bak后缀
#!/bin/bash
DIR=/data/test
cd $DIR || { echo 无法进入$DIR;exit 1; }
for FILE in *;do
PRE=`echo $FILE | grep -Eo ".*\."`
mv $FILE ${PRE}.bak
done
2022-2-2