目录
1.9 * 9 乘法表,for列表循环,for循环(c语言风格), while循环
2.使用for循环创建30个用户: test01~test30, 并设置密码为test01123456~test30123456
3.使用循环去判断网段内的IP(1~254),本机除外,可以ping通的使用 ssh远程登录
5.使用循环去读取文件内容并输出: 3中方式(1.exec+while循环 2.管道符+while循环 3.重定向+while)
1.9 * 9 乘法表,for列表循环,for循环(c语言风格), while循环
可选单层循环
for列表循环
[root@server shell]# vim multiplication_table.sh
result=0
for a in {1..9}
do
for b in {1..9}
do
result=$[a * b]
if [ $a -ge $b ]
then
echo -n " $a*$b=`printf "%02g" $result`"
fi
done
echo -e "\n"
done
for循环(c语言风格)
result=0
for ((m=1;m<10;m++))
do
for ((n=1;n<=m;n++))
do
result=$[m*n]
echo -n " $m*$n=`printf "%02g" $result`"
done
echo -e "\n"
done
while循环
x=1
y=1
while [ $x -lt 10 ]
do
y=1
while [ $y -le $x ]
do
result=$[x*y]
echo -n " $x*$y=`printf "%02g" $result`"
let y++
done
echo ""
let x++
done
2.使用for循环创建30个用户: test01~test30, 并设置密码为test01123456~test30123456
[root@server shell]# bash useradd.sh
for i in {1..30}
do
nu=`printf "%02g" $i`
useradd test$nu
echo "test"$nu"123456" | passwd --stdin test$nu
done
3.使用循环去判断网段内的IP(1~254),本机除外,可以ping通的使用 ssh远程登录
[root@server shell]# vim ping_ssh.sh
for i in {1..254}
do
ping -c 3 -i 0.5 -W 1 192.168.110.$i &> /dev/null
if test $? -eq 0
then
echo "192.168.110.$i is up"
ssh root@192.168.110.$i
else
echo "192.168.110.$i is down"
fi
done
4.使用$@和$*作为for循环后的列表,并体现出区别
变量 | |
$* | 以"参数1 参数2 参数3…"的形式返回所有参数的值 |
$@ | 以“参数1”“参数2”“参数3”…的形式返回所有的值 |
[root@server shell]# vim different.sh
echo $0
for i in "$*"
do
echo $i
done
echo "******************"
for i in "$@"
do
echo $i
done
[root@server shell]# bash different.sh 123 456
a.sh
123 456
******************
123
456
5.使用循环去读取文件内容并输出: 3中方式(1.exec+while循环 2.管道符+while循环 3.重定向+while)
[root@server shell]# bash read_file.sh
exec < file
while read a
do
echo $a
done
echo "*************"
while read b
do
echo $b
done < file
echo "*************"
cat file |while read c
do
echo $c
done