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
相关推荐
Pythonliu74 小时前
茴香豆 + Qwen-7B-Chat-Int8
linux·运维·服务器
你疯了抱抱我4 小时前
【RockyLinux 9.4】安装 NVIDIA 驱动,改变分辨率,避坑版本。(CentOS 系列也能用)
linux·运维·centos
小O_好好学5 小时前
CentOS 7文件系统
linux·运维·centos
哲伦贼稳妥6 小时前
一天认识一个硬件之机房地板
运维·网络·经验分享·其他
john_hjy6 小时前
11. 异步编程
运维·服务器·javascript
x晕x6 小时前
Linux dlsym符号查找疑惑分析
linux·运维·服务器
活跃的煤矿打工人7 小时前
【星海saul随笔】Ubuntu基础知识
linux·运维·ubuntu
tangdou3690986557 小时前
两种方案手把手教你多种服务器使用tinyproxy搭建http代理
运维·后端·自动化运维
北京智和信通7 小时前
云平台和虚拟化智慧运维监控,全面提升故障感知与处置能力
运维·虚拟化·云平台·虚拟机监控
fasewer7 小时前
第五章 linux实战-挖矿 二
linux·运维·服务器