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
相关推荐
极验1 分钟前
iPhone17实体卡槽消失?eSIM 普及下的安全挑战与应对
大数据·运维·安全
爱倒腾的老唐5 分钟前
24、Linux 路由管理
linux·运维·网络
yannan2019031311 分钟前
Docker容器
运维·docker·容器
_清浅13 分钟前
计算机网络【第六章-应用层】
运维·服务器·计算机网络
正在努力的小河24 分钟前
Linux 自带的 LED 灯驱动实验
linux·运维·服务器
李子圆圆31 分钟前
电力专用多功能微气象监测装置在电网安全运维中的核心价值是什么?
运维·安全
花开富贵贼富贵33 分钟前
MySQL 核心高级特性
运维·数据库·mysql
小宁爱Python1 小时前
Windows Docker Desktop占用C盘空间过大解决办法集合
运维·docker·容器
恒创科技HK2 小时前
如何选30G、60G、100G的香港高防服务器?
运维·服务器
wanhengidc2 小时前
云手机 手游专用虚拟手机
运维·服务器·安全·游戏·智能手机