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
相关推荐
有梦想的咕噜40 分钟前
`README`、`LICENSE` 和 `.gitignore` 是非常常见的文件
运维
沉默的八哥1 小时前
如何配置 Horizontal Pod Autoscaler (HPA)
运维·kubernetes
P7进阶路2 小时前
nginx 代理 redis
运维·redis·nginx
已是上好佳3 小时前
整理了一下网络编程中TCP的状态
运维·服务器·网络
技术小齐3 小时前
网络运维学习笔记(DeepSeek优化版) 014网工初级(HCIA-Datacom与CCNA-EI)NAT网络地址转换
运维·网络·学习
菜萝卜子3 小时前
【Linux】权限相关知识点
linux·运维·服务器
热心市民运维小孙3 小时前
weblogic部署报错汇总
运维
LG.YDX4 小时前
Linux:理解进程,系统调用,进程,进程切换,调度,分时操作系统和实时操作系统,
linux·运维·服务器
weifexie8 小时前
linux awk命令和awk语言
linux·运维·服务器
m0_748238279 小时前
Nginx解决前端跨域问题
运维·前端·nginx