Shell中的for循环可以用来迭代一个列表或者一个范围内的值。

语法:

for variable in list
do
   command1
   command2
   ...
   commandN
done

其中,'list'可以是一个用空格分隔的字符串,也可以是一个包含多个元素的数组。循环会依次遍历'list'中的每一个元素,并执行循环体内的命令,直到遍历完所有元素。

例子:

#!/bin/bash

for i in 1 2 3 4 5
do
   echo 'Value of i is $i'
done

输出:

Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5

使用范围迭代:

#!/bin/bash

for i in {1..5}
do
   echo 'Value of i is $i'
done

输出:

Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5

使用命令的输出作为循环列表:

#!/bin/bash

for user in $(cat /etc/passwd | cut -d: -f1)
do
   echo 'User: $user'
done

输出:

User: root
User: daemon
User: bin
User: sys
User: sync
User: games
User: ...

处理包含空格等特殊字符的元素:

当循环列表中的元素包含空格等特殊字符时,需要使用引号将其括起来,例如:

#!/bin/bash

for file in '/tmp/file1' '/tmp/file2 with space' '/tmp/file3'
do
   echo 'File: $file'
done

输出:

File: /tmp/file1
File: /tmp/file2 with space
File: /tmp/file3
Shell For循环详解:语法、示例及应用场景

原文地址: https://www.cveoy.top/t/topic/odmJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录