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, 并设置密码为test01 123456~test30 123456
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远程登录
for i in `seq 1 254`
do
if [ $i -eq 135 ];then
continue
else
ping -c 2 -w 1 192.168.10.$i &> /dev/null
if [ $? -eq 0 ];then
ssh 192.168.10.$i
fi
fi
done
4.使用 @ 和 @和 @和*作为for循环后的列表,并体现出区别
[root@servera bash]# bash @and\*.sh this is a example
echo "============$ @================"
for i in "$@"
do
echo $i
done
echo "============$ *================"
for i in "$*"
do
echo $*
done
[root@servera bash]# bash @and*.sh this is a example
============$ @================
this
is
a
example
============$ *================
this is a example
[root@servera bash]#
5.使用循环去读取文件内容并输出: 3中方式(1.exec+while循环 2.管道符+while循环 3.重定向+while)
[root@servera bash]# echo data{1..3} > file.txt
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@servera bash]# bash while_read.sh
============= methon 1:exec+while ================
data1 data2 data3
============= methon 2: | +while ================
data1 data2 data3
============= methon 3: < +while ================
data1 data2 data3