

您可以通过多种方式在bash脚本上申请循环。本文提到了一些有用的BASH for循环示例。
这是Bash For循环采用以下形式的示例:
for item in [LIST] do [COMMANDS] done
现在,让我们看一下标准的Bash for String over Strings:
for element in Gold Silver Diamond Platinum do echo \"Element: $element\" Done
让我们看下面的示例,该示例将从数字开始迭代:
from 2 to 6.
for i in {2..6}for i in {
dodo
echo \"Number: $i\"\"Number: $i\"
donedone
尽管可以将for循环用于数字和字符串,但程序员甚至可以利用它们在一定范围内重复。例如:
PLAYERS=(\'meilana\' \'maria\' \'ulfa\')=(\'meilana\' \'maria\'
for player in \"${PLAYERS[@]}\"; dofor player in \"${PLAYERS[@]}\";
echo \"Player: $player\"\"Player: $player\"
donedone
break和continue语句可用于控制for循环的执行。
违约声明
要使用break语句,用户必须指定一个特定条件,当条件满足时将中断循环。当程序员想要在计划之前停止for循环时,他们甚至
for element in Gold Silver Diamond Platinum; do element in Gold Silver Diamond Platinum; if [[ \"$element\" == \'Diamond\' ]]; thenif [[ \"$element\" == \'Diamond\' ]]; breakbreak fifi echo \"Element: $element\"\"Element: $element\" donedone echo \'All Done!\'\'All Done!\'
继续声明
Continue语句退出循环的当前迭代,并将程序控制传递给循环的下一个迭代。例如,让我们使用continue语句迭代一个数字范围,当它达到一个特定的数字(在本例中为“ 6”)时,continue语句将退出迭代并返回到该数字的开头。循环以开始下一个迭代:
for i in {2..8}; do i in {2..8};
if [[ \"$i\" == \'6\' ]]; thenif [[ \"$i\" == \'6\' ]]; then
continuecontinue
fifi
echo \"Number: $i\"\"Number: $i\"
donedone
在bash中使用For循环有两种方法,一种是“ c样式语法”,另一种是“ for-in”。C样式的for循环的语法如下:
for ((INITIALIZATION; TEST; STEP)) ((INITIALIZATION; TEST; STEP)) dodo [COMMANDS][COMMANDS] donedone Meanwhile, as aforementioned, the ‘for-in’ loop will take the following form:Meanwhile, as aforementioned, the ‘for-in’ loop will take the following form: for variable in listfor variable in list dodo StatementsStatements DoneDone
循环读取输入变量
这是如何将它们用于循环的示例。在该示例中,我们将采用文本的输入值,该文本具有在执行脚本之后将采用的多个单词。我们将使用for循环根据空白分隔预定义的文本。然后确保脚本将打印每个单词:
#!/bin/bash echo \"Enter a text of multiple words\"\"Enter a text of multiple words\" read text i=1=1 for word in $textfor word in $text dodo echo \"Word No-$i = $word\"\"Word No-$i = $word\" ((i=$i+1))((i=$i+1)) donedone
然后运行以下脚本:
bash forloop1.sh.sh
用break语句循环
程序员可以使用for循环语句读取和打印当前目录的文件和文件夹列表。首先,创建一个文件名并执行以下脚本。用户必须注意,“ *”用于读取“ for循环”中的文件。循环的功能是一种简单的方式,方法是通过目录的步骤读取每个文件或文件夹,并在终端的\’tab\’空间打印输出:
printf \"Pinting the files and folders of the current Directory...\\n\\n\"\"Pinting the files and folders of the current Directory...\\n\\n\" for list in *for list in * dodo printf \"$list\\t\"\"$list\\t\" donedone printf \"\\n\\nDone\\n\"\"\\n\\nDone\\n\"
然后,运行以下脚本:
bash forloop1.sh.sh
更改文件扩展名
使用for循环,可以更改当前目录中所有文件的文件扩展名。例如,我们将使用for循环将所有.jpeg文件替换为.png文件:
for file in *.jpeg; do file in *.jpeg; do
mv -- \"$file\" \"${file%.jpeg}.png\"-- \"$file\" \"${file%.jpeg}.png\"
donedone
恭喜你!您已经通过示例成功学习了Bash For Loop。有关其他帮助或有用信息,我们建议您检查Bash官方网站。