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
相关推荐
jingyu飞鸟5 分钟前
linux系统源代码安装apache、编译隐藏版本号
linux·运维·apache
2401_858286111 小时前
OS15.【Linux】gdb调试器的简单使用
linux·运维·服务器·开发语言·gdb
c30%003 小时前
内网渗透——红日靶场五
运维·服务器
宇钶宇夕3 小时前
EPLAN 电气制图:建立自己的部件库,添加部件-加SQL Server安装教程(三)上
运维·服务器·数据库·程序人生·自动化
susu10830189114 小时前
Debian 11 Bullseye 在线安装docker
运维·docker·debian
love530love4 小时前
Docker 稳定运行与存储优化全攻略(含可视化指南)
运维·人工智能·windows·docker·容器
岁岁岁平安4 小时前
CentOS-7-x86_64解决:使用NAT模式无法ping通www.baidu.com或无法ping 8.8.8.8问题。
linux·运维·centos·centos-7
运维小贺5 小时前
各服务器厂商调整BIOS睿频教程
linux·运维·服务器·性能优化
网硕互联的小客服5 小时前
如何排查服务器中已经存在的后门程序?
运维·服务器·github
人生匆匆5 小时前
docker进入启动失败的容器
运维·docker·容器