1.9 * 9 乘法表,for列表循环,for循环(c语言风格), while循环
可选单层循环
2.使用for循环创建30个用户: test01~test30, 并设置密码为test01123456~test30123456
3.使用循环去判断网段内的IP(1~254),本机除外,可以ping通的使用 ssh远程登录
4.使用$@和$*作为for循环后的列表,并体现出区别
5.使用循环去读取文件内容并输出: 3中方式(1.exec+while循环 2.管道符+while循环 3.重定向+while)
1.9 * 9 乘法表,for列表循环,for循环(c语言风格), while循环
可选单层循环
#! /bin/bash
echo "==================for i in list==================="
for i in `seq 9`
do
for j in `seq $i`
do
echo -n "$i*$j=$[i*j] "
done
echo
done
echo "==================for(())==================="
for((i=1,j=1;i<=9;j++))
do
echo -n "$i*$j=$[i*j] "
if [ $i == $j ];then
echo -e '\n'
let j=0
let i=$i+1
fi
done
echo "==================while==================="
let i=1;
while ((i<=9))
do
let j=1;
while (($j<=$i))
do
echo -ne "$i"*"$j=$[i*j]\t"
let j++;
done
echo ""
let i++;
done
2.使用for循环创建30个用户: test01~test30, 并设置密码为test01123456~test30123456
#!/bin/bash
for i in `seq -f '%02g' 1 30`
do
if id -u $i &> /dev/null;then
echo test$i is exist!
continue
fi
useradd test$i
echo "test'$i'123456" | passwd --stdin test$i &> /dev/null
done
3.使用循环去判断网段内的IP(1~254),本机除外,可以ping通的使用 ssh远程登录
#!/bin/bash
for i in `seq 1 254`
do
if [ $i -eq 135 ];then
continue
else
ping -c 2 -w 1 192.168.248.$i &> /dev/null
#192.168.248.$i 为本机ip网段
if [ $? -eq 0 ];then
ssh 192.168.248.$i
fi
fi
done
4.使用$@和$*作为for循环后的列表,并体现出区别
echo "============$ @================"
for i in "$@"
do
echo $i
done
echo "============$ *================"
for i in "$*"
do
echo $*
done
[root@localhost task_4]# sh @and\*_for.sh welcome to china
============$ @================
welcome
to
china
============$ *================
welcome to china
5.使用循环去读取文件内容并输出: 3中方式(1.exec+while循环 2.管道符+while循环 3.重定向+while)
#File name:while.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-27 23:26:13
#Description:
#########################
echo "============= methon 1:exec+while ================"
exec < file.txt
while read a
do
echo $a
done
echo "============= methon 2: | +while ================"
cat file.txt | while read line
do
echo $line
done
echo "============= methon 3: < +while ================"
while read line
do
echo $line
done < file.txt
[root@localhost task_4]# sh while.sh
============= methon 1:exec+while ================
welcome to China
fucking America
Japan is pig
============= methon 2: | +while ================
welcome to China
fucking America
Japan is pig
============= methon 3: < +while ================
welcome to China
fucking America
Japan is pig