shell--for循环

1.带列表for循环

语法格式

bash 复制代码
for 循环变量 in 列表
do
	执行语句
	...
done

在上面的语法中,循环变量是每次循环时得到的列表的某一个数据,当循环一次结束后,再获取另一个数,然后再执行 do 里面的语句,依次类推,直到列表中数据循环完结。

for 循环中的列表中的数据是以空格来进行分隔的

示例:直接列出列表的所有元素

bash 复制代码
[root@openEuler ~]# cat for1.sh
#!/bin/bash

for var in 192.168.72.130 192.168.72.131 192.168.72.132
do
	echo $var
done
[root@openEuler ~]# bash for1.sh
192.168.72.130
192.168.72.131
192.168.72.132

在带列表的for循环中,还可以指定循环的步长,它的语法格式为:

bash 复制代码
for 循环变量 in {开始..结束..步长}
do
   语句
   ....
done

示例:循环输入 1~10中的奇数

bash 复制代码
[root@openEuler ~]# cat for2.sh 
#!/bin/bash

for v in {1..10..2}
do
	echo $v
done
[root@openEuler ~]# bash for2.sh 
1
3
5
7
9

示例:获取根目录下所有文件名作为变量的值打印输出。

bash 复制代码
[root@openEuler ~]# cat for3.sh 
#!/bin/bash

for file in $(ls -F / | grep -v /$)
do
	echo $file
done


[root@openEuler ~]# bash for3.sh 
bin@
lib@
lib64@
sbin@

示例:打印出如下的语句中字符数不大于6的单词。

bash 复制代码
[root@openEuler ~]# cat for4.sh 
#!/bin/bash

for word in hello world rabbit favorite eat apple cabbage
do
	if [ `expr length ${word}` -le 6 ]; then
		echo $word
	fi
done
[root@openEuler ~]# bash for4.sh 
hello
world
rabbit
eat
apple

2.不带列表循环

语法格式:

bash 复制代码
for 循环变量
do
	语句
	...
done

示例:循环输入所有的参数

bash 复制代码
[root@openEuler ~]# cat for5.sh
#!/bin/bash

for v in $@
do
	echo $v
done
[root@openEuler ~]# bash for5.sh 
[root@openEuler ~]# bash for5.sh {1..5}
1
2
3
4
5

3.类C风格循环

语法格式:

bash 复制代码
for ((表达式1;表达式2;表达式3))
do
	语句
done

示例:批量创建用户,用户名以 test 开头,按数字序号变化。一共添加 30 个账号,名称如:test01、test02、...、test10、....test30 用户初始密码为 Abc123456

bash 复制代码
[root@openEuler ~]# cat for6.sh
#!/bin/bash

for ((i=1;i<=30;i++))
do
	if [ $i -lt 10 ]; then
		user=test0$i
	else
		user=test$i
	fi
	if ! id -u $user &> /dev/null
	then
		useradd $user
		echo "Abc123456" | passwd --stdin $user &> /dev/null
	else
		echo "$user is exists"
	fi
done

[root@openEuler ~]# bash for6.sh
[root@openEuler ~]# grep test /etc/passwd
test01:x:1001:1001::/home/test01:/bin/bash
test02:x:1002:1002::/home/test02:/bin/bash
test03:x:1003:1003::/home/test03:/bin/bash
test04:x:1004:1004::/home/test04:/bin/bash
相关推荐
野生派蒙28 分钟前
Linux:安装 CentOS 7(完整教程)
linux·运维·服务器·centos
肯德基疯狂星期四-V我501 小时前
【Ubuntu】【树莓派】Linux系统的远程终端登录、远程图形桌面访问、 X图形窗口访问和文件传输操作
linux·运维·ubuntu·树莓派
努力努力再努力wz1 小时前
【Linux实践系列】:匿名管道收尾+完善shell外壳程序
linux·运维·服务器·c++
阵雨会停.2 小时前
Linux 使用Nginx搭建简易网站模块
运维·nginx
超級二蓋茨2 小时前
局域网内Docker镜像共享方法
运维·docker·容器
CAE虚拟与现实2 小时前
Ubuntu中snap
linux·运维·ubuntu·apt·wsl·wsl2·snap
梁萌3 小时前
05-DevOps-Jenkins自动拉取构建代码
运维·jenkins·devops·代码拉取
人猿泰飞3 小时前
在Ubuntu-22.04.5中安装ONLYOFFICE DocSpace(协作空间)【注意:安装失败,谨慎参考!】
java·linux·运维·python·ubuntu·项目管理·onlyoffice
CAE虚拟与现实3 小时前
修改wsl中发行版Ubuntu的主机名
linux·运维·ubuntu·wsl·wsl2·修改主机名
开发小能手-roy3 小时前
Ubuntu服务器性能调优指南:从基础工具到系统稳定性提升
linux·运维·服务器·ubuntu