实例
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)
9 * 9 乘法表,for列表循环,for循环(c语言风格), while循环
for列表循环版,如下:
#!/bin/bash
#########################
#File name:9*9.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-19 19:35:13
#Description:
#########################
for a in {1..9}
do
for b in {1..9}
do
let data=$a'*'$b
if [ $a -eq $b ]
then echo -e "$a * $b = $data\n"
elif [ $a -gt $b ]
then echo -n "$a * $b = $data "
fi
done
done
while循环,单层循环版,如下:
#!/bin/bash
#########################
#File name:9*9_2.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-21 18:57:18
#Description:
#########################
a=1
b=1
while [ $a -le 9 ]
do
let data=$a*$b
if [ $a -eq $b ]
then echo -e "$a * $b = $data\n"
let a++;b=1
elif [ $a -gt $b ]
then echo -n "$a * $b = $data ";let b++
fi
done
以上结果如下:
使用for循环创建30个用户: test01~test30
并设置密码为test01123456~test30123456
for循环创建,代码如下:
用户名后缀通过
user=`printf %02g $i`获得
#!/bin/bash
#########################
#File name:for_script_useradd.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-21 19:49:29
#Description:
#########################
for i in {1..30}
do
user=`printf %02g $i`
useradd test$user
echo "test"$user"123456" |passwd --stdin test$user
done
使用while循环删除用户,记得加上-r删除用户主目录,代码如下:
#!/bin/bash
#########################
#File name:while_script_userdel.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-21 20:48:15
#Description:
#########################
i=1
while [ $i -le 30 ]
do
user=`printf %02g $i`
userdel -r test$user
let i++
done
结果展示:
使用$@和$*作为for循环后的列表,并体现出区别
再次强调,$@和$*的区别
$@是 将输入变量划分为多个字符串
$*是 将输入变量作为单个字符串
代码如下:
ps:\"是为了在输出时方便观看
#!/bin/bash
#########################
#File name:for_script_and%*.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-21 19:59:53
#Description:
#########################
for i in "$@"
do
echo "$i"
done
for i in "\"$*\""
do
echo "$i"
done
输入结果如图:
使用循环去读取文件内容并输出: 3种方式
1.重定向+while
2.exec+while循环
3.管道符+while循环
#!/bin/bash
#########################
#File name:while_script_readfile.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-21 20:05:15
#Description:
#########################
while read a
do
echo $a
done <file
echo '----------------'
exec <file
while read a
do
echo $a
done
echo '----------------'
cat file | while read a
do
echo $a
done